dongxiejie9387 2015-05-31 17:09 采纳率: 100%
浏览 53

使用Go中的libproc.h处理OS X的CPU使用情况

I known that excellent replies exist on the subject for questions like:

The problem is that I'm trying to use libproc.h that defines a proc_threadinfo structure (among others) but the field pth_cpu_usage is always 0 (see trheadInfoHandler() func here to see how I'm using the struct from Go).

Looking at a snippet of Chromium source here (that doesn't use libproc.h), I was wondering if using fields from both proc_threadinfo and proc_taskinfo it could be possible calculate cpu percent usage.


proc_threadinfo.pth_user_time; /* user run time */
proc_threadinfo.pth_system_time; /* system run time */

proc_taskinfo.pti_total_user; /* total time */
proc_taskinfo.pti_total_system;

Edit

Some pseudo code illustrating the right algorithm or a suggestion to put me on the right path will be very appreciated.

Using /proc filesystem I think I was able to calculate CPU % usage in Linux:


func cpuUsageOf(pid int, waitHandler func()) float32 {
    stat1 := procFsStatOf(pid)
    utime1 := stat1.utime // /proc/[pid]/stat field index 13
    stime1 := stat1.stime // /proc/[pid]/stat field index 14
    cputime1 := procFsCpuTimeTotal() // /proc/stat -> sum of cpu values

    waitHandler() // here I wait 1 second

    stat2 := procFsStatOf(pid)
    utime2 := stat2.utime // /proc/[pid]/stat field index 13
    stime2 := stat2.stime // /proc/[pid]/stat field index 14
    cputime2 := procFsCpuTimeTotal() // /proc/stat -> sum of cpu values

    return float32(cpuCount() * ((utime2 + stime2) - (utime1 + stime1)) * 100) / float32(cputime2 - cputime1)
}

For OS X, do I've to use values from proc_threadinfo or proc_taskinfo? And where I can find the same values that in Linux I read from /proc/stat with (procFsCpuTimeTotal())?

Full code here (as in commit 9e34d3c72bf853ff49ef3970ad6a6c9688e9ba23); fast link to OS X code here.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)