如何计算C中的进程CPU使用率?

时间:2023-02-05 20:34:55

I'm writing a process explorer project.
I can get some Information about processes using Win32 Tool Help Snapshot.
but I can't calculate the amount of CPU usage of each process.
It's a C Window Console Application.

我正在编写一个流程资源管理器项目。我可以使用Win32 Tool Help Snapshot获取有关进程的一些信息。但我无法计算每个进程的CPU使用量。这是一个C Window控制台应用程序。

1 个解决方案

#1


0  

Maybe the ISO C standardized clock() function does what you need.

也许ISO C标准化clock()函数可以满足您的需求。

$ man clock

$ man clock

NAME clock — determine processor time used

NAME时钟 - 确定使用的处理器时间

LIBRARY Standard C Library (libc, -lc)

LIBRARY标准C库(libc,-lc)

SYNOPSIS #include < time.h>

大纲#include

 clock_t
 clock(void);

DESCRIPTION The clock() function determines the amount of processor time used since the invocation of the calling process, measured in CLOCKS_PER_SECs of a second.

描述clock()函数确定自调用调用进程以来使用的处理器时间量,以一秒钟的CLOCKS_PER_SEC为单位进行测量。

RETURN VALUES The clock() function returns the amount of time used unless an error occurs, in which case the return value is -1.

返回值clock()函数返回使用的时间量,除非发生错误,在这种情况下返回值为-1。

You would call it once at the start of main(), save the result and later on compute (clock() - result)/CLOCKS_PER_SEC (beware of rounding for integral division!).

你可以在main()的开头调用它一次,保存结果,然后保存在compute(clock() - result)/ CLOCKS_PER_SEC(注意整数除法的舍入!)。

#1


0  

Maybe the ISO C standardized clock() function does what you need.

也许ISO C标准化clock()函数可以满足您的需求。

$ man clock

$ man clock

NAME clock — determine processor time used

NAME时钟 - 确定使用的处理器时间

LIBRARY Standard C Library (libc, -lc)

LIBRARY标准C库(libc,-lc)

SYNOPSIS #include < time.h>

大纲#include

 clock_t
 clock(void);

DESCRIPTION The clock() function determines the amount of processor time used since the invocation of the calling process, measured in CLOCKS_PER_SECs of a second.

描述clock()函数确定自调用调用进程以来使用的处理器时间量,以一秒钟的CLOCKS_PER_SEC为单位进行测量。

RETURN VALUES The clock() function returns the amount of time used unless an error occurs, in which case the return value is -1.

返回值clock()函数返回使用的时间量,除非发生错误,在这种情况下返回值为-1。

You would call it once at the start of main(), save the result and later on compute (clock() - result)/CLOCKS_PER_SEC (beware of rounding for integral division!).

你可以在main()的开头调用它一次,保存结果,然后保存在compute(clock() - result)/ CLOCKS_PER_SEC(注意整数除法的舍入!)。