获取CPU使用率IOS Swift [英] Get CPU usage IOS Swift

查看:451
本文介绍了获取CPU使用率IOS Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取单个应用程序的总体CPU使用率.我找到了一些资源,但是它们要么是用C编写的,要么是过时的.谁能帮助我解决这个问题?我试图将其转换为 https://github.com/beltex /SystemKit/blob/master/SystemKit/System.swift#L12 迅速.

I am trying to get overall CPU usage not of a single app. I found some of the resources but they are either written in C or outdated swift. Can anyone help me with this problem? I am trying to conver this https://github.com/beltex/SystemKit/blob/master/SystemKit/System.swift#L12 to swift.

到目前为止,我能够进行如此多的转换

Till now I am able to convert this much

fileprivate func hostCPULoadInfo() -> host_cpu_load_info{

        let  HOST_CPU_LOAD_INFO_COUNT = MemoryLayout<host_cpu_load_info>.stride / MemoryLayout<integer_t>.stride;

        var size = mach_msg_type_number_t(HOST_CPU_LOAD_INFO_COUNT);
        var hostInfo = host_cpu_load_info_t.allocate(capacity: 1);

        let result = withUnsafeMutablePointer(to: &hostInfo) {$0.withMemoryRebound(to: integer_t.self, capacity: Int(size)){
            host_info(mach_host_self(), Int32(HOST_BASIC_INFO), $0, &size)
            }
        }

        let data = hostInfo.move()
        hostInfo.deallocate(capacity: 1)


        #if DEBUG
            if result != KERN_SUCCESS{
                print("Error  - \(#file): \(#function) - kern_result_t = \(result)");
            }
        #endif

        return data;
    }

public func cpuUsage() -> (system: Double, user: Double, idle : Double, nice: Double){
        let load = hostCPULoadInfo();

        let usrDiff: Double = Double(load.cpu_ticks.0 - loadPrevious.cpu_ticks.0);
        let systDiff = Double(load.cpu_ticks.1 - loadPrevious.cpu_ticks.1);
        let idleDiff = Double(load.cpu_ticks.2 - loadPrevious.cpu_ticks.2);
        let niceDiff = Double(load.cpu_ticks.3 - loadPrevious.cpu_ticks.3);

        let totalTicks = usrDiff + systDiff + idleDiff + niceDiff
        print("Total ticks is ", totalTicks);
        let sys = systDiff / totalTicks * 100.0
        let usr = usrDiff / totalTicks * 100.0
        let idle = idleDiff / totalTicks * 100.0
        let nice = niceDiff / totalTicks * 100.0

        return (sys, usr, idle, nice);
    }

但是问题是我遇到了这样的错误

But the thing is I am getting an error like this

Error  - /Users/administrator/Downloads/Documents/Swift/SystemInfo/RAMInformation.swift: hostCPULoadInfo() - kern_result_t = 5

有人知道上面的代码有什么问题吗?我对host_statistics的转换做错了.

Does anybody knows what's wrong in the above code? I thing I am doing wrong on conversion of host_statistics.

有人可以帮助我吗?

推荐答案

您的代码中存在三个错误:

There are three errors in your code:

  • CPU统计信息是通过调用host_statistics()获得的,而不是通过 host_info().
  • 风味"参数必须为HOST_CPU_LOAD_INFO,而不是HOST_BASIC_INFO.
  • hostInfo包含指向已分配结构的指针, 因此该值必须是反弹值,而不是变量的地址.
  • The CPU statistics is obtained by calling host_statistics(), not host_info().
  • The "flavor" argument must be HOST_CPU_LOAD_INFO, not HOST_BASIC_INFO.
  • hostInfo contains the pointer to the allocated structure, so that value must be rebound, not the address of the variable.

将它们放在一起:

func hostCPULoadInfo() -> host_cpu_load_info? {

    let  HOST_CPU_LOAD_INFO_COUNT = MemoryLayout<host_cpu_load_info>.stride / MemoryLayout<integer_t>.stride

    var size = mach_msg_type_number_t(HOST_CPU_LOAD_INFO_COUNT)
    let hostInfo = host_cpu_load_info_t.allocate(capacity: 1)

    let result = hostInfo.withMemoryRebound(to: integer_t.self, capacity: HOST_CPU_LOAD_INFO_COUNT) {
        host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &size)
    }

    if result != KERN_SUCCESS{
        print("Error  - \(#file): \(#function) - kern_result_t = \(result)")
        return nil
    }
    let data = hostInfo.move()
    hostInfo.deallocate(capacity: 1)
    return data
}

(我将返回类型更改为可选,以便可以返回nil 在错误的情况下).

(I changed the return type to an optional so that nil can be returned in the error case).

或者,使用局部变量而不是分配和释放 host_cpu_load_info结构:

Alternatively, use a local variable instead of allocating and releasing the host_cpu_load_info structure:

func hostCPULoadInfo() -> host_cpu_load_info? {
    let HOST_CPU_LOAD_INFO_COUNT = MemoryLayout<host_cpu_load_info>.stride/MemoryLayout<integer_t>.stride
    var size = mach_msg_type_number_t(HOST_CPU_LOAD_INFO_COUNT)
    var cpuLoadInfo = host_cpu_load_info()

    let result = withUnsafeMutablePointer(to: &cpuLoadInfo) {
        $0.withMemoryRebound(to: integer_t.self, capacity: HOST_CPU_LOAD_INFO_COUNT) {
            host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &size)
        }
    }
    if result != KERN_SUCCESS{
        print("Error  - \(#file): \(#function) - kern_result_t = \(result)")
        return nil
    }
    return cpuLoadInfo
}

这篇关于获取CPU使用率IOS Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆