How to get the CPU Usage in C?

邮差的信 提交于 2019-12-30 18:52:19

问题


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.


回答1:


This is platform-specific:

  • In Windows, you can use the GetProcessTimes() function.
  • In Linux, you can actually just use 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:

% CPU usage = (CPU time) / (# of cores) / (wall time)

Getting the # of logical cores is also platform-specific:

  • Windows: GetSystemInfo()
  • Linux: sysconf(_SC_NPROCESSORS_ONLN)



回答2:


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).




回答3:


It is usually operating system specific.

You could use the clock function, returning a clock_t (some integer type, like perhaps long). On Linux systems it measures the CPU time in microseconds.




回答4:


that is the exact thing I was looking for. Manipulating it in my way, I run it successfully.

Get total CPU usage



来源:https://stackoverflow.com/questions/8501706/how-to-get-the-cpu-usage-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!