简体   繁体   English

获取CPU使用率IOS Swift

[英]Get CPU usage IOS Swift

I am trying to get overall CPU usage not of a single app. 我正在尝试获取单个应用程序的总体CPU使用率。 I found some of the resources but they are either written in C or outdated swift. 我找到了一些资源,但是它们要么是用C编写的,要么是过时的。 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. 我正在尝试将这个https://github.com/beltex/SystemKit/blob/master/SystemKit/System.swift#L12转换为快速。

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

Does anybody knows what's wrong in the above code? 有人知道上面的代码有什么问题吗? I thing I am doing wrong on conversion of host_statistics. 我对host_statistics的转换做错了。

Can anybody help me? 有谁能够帮助我?

There are three errors in your code: 您的代码中存在三个错误:

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

Putting it all together: 放在一起:

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
}

(I changed the return type to an optional so that nil can be returned in the error case). (我将返回类型更改为可选类型,以便在错误情况下可以返回nil )。

Alternatively, use a local variable instead of allocating and releasing the host_cpu_load_info structure: 或者,使用局部变量而不是分配和释放host_cpu_load_info结构:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM