C语言中如何获取CPU使用率?
我想获得 C 语言中应用程序的总 CPU 使用率,就像我们在 TaskManager 中获得的总 CPU 使用率... 我想知道...对于 windows 和 linux:: 当前所有进程的 CPU 总利用率 ..... 正如我们在任务管理器中看到的那样。
I want to get the overall total CPU usage for an application in C, the total CPU usage like we get in the TaskManager...
I want to know ... for windows and linux :: current Total CPU utilization by all processes ..... as we see in the task manager.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是特定于平台的:
GetProcessTimes()
函数。clock()
。这些可用于测量两个时间间隔之间占用的 CPU 时间量。
编辑:
要获取 CPU 消耗(以百分比表示),您需要将总 CPU 时间除以操作系统看到的逻辑核心数量,然后除以总挂钟时间:
获取逻辑核心的数量也是特定于平台的:
GetSystemInfo()
sysconf(_SC_NPROCESSORS_ONLN)
This is platform-specific:
GetProcessTimes()
function.clock()
.These can be used to measure the amount of CPU time taken between two time intervals.
EDIT :
To get the CPU consumption (as a percentage), you will need to divide the total CPU time by the # of logical cores that the OS sees, and then divided by the total wall-clock time:
Getting the # of logical cores is also platform-specific:
GetSystemInfo()
sysconf(_SC_NPROCESSORS_ONLN)
在 POSIX 下,您需要 getrusage(2) 的 ru_utime 字段。仅将 RUSAGE_SELF 用于调用进程,并将 RUSAGE_CHILDEN 用于所有已终止和 wait(2) 的子进程。 Linux 还仅支持调用线程的 RUSAGE_THREAD。如果您需要系统时间,请使用 ru_stime,系统时间可以与 ru_utime 相加,得出活动运行的总时间(不是挂机时间)。
Under POSIX, you want getrusage(2)'s ru_utime field. Use RUSAGE_SELF for just the calling process, and RUSAGE_CHILDEN for all terminated and wait(2)ed-upon children. Linux also supports RUSAGE_THREAD for just the calling thread. Use ru_stime if you want the system time, which can be summed with ru_utime for total time actively running (not wall time).
它通常是特定于操作系统的。
您可以使用 clock 函数,返回一个
clock_t
(某些整数类型,例如long
)。在 Linux 系统上,它以微秒为单位测量 CPU 时间。It is usually operating system specific.
You could use the clock function, returning a
clock_t
(some integer type, like perhapslong
). On Linux systems it measures the CPU time in microseconds.