简体   繁体   English

在C中获取进程Cpu使用情况

[英]GET Process Cpu Usage In c

How can i Get process Cpu usage in c?? 我如何在C中获取进程Cpu使用率?

I need Cpu usage of evrey process and threads. 我需要evrey进程和线程的Cpu使用率。

please give me an example. 请给我一个例子。

Thanks! 谢谢!

In C, total CPU usage can be determined using Performance Counters (there is a small typo in the example code: sleep has to be changed to Sleep ). 在C语言中,可以使用性能计数器来确定CPU的总使用量 (示例代码中有一个小的错字: sleep必须更改为Sleep )。

In C++, C#, Delphi etc., I would recommend using WMI . 在C ++,C#,Delphi等中,我建议使用WMI

== EDIT == ==编辑==

I found an approach to get the per-process CPU usage . 我找到了一种获取每个进程CPU使用率的方法 For example, in order to get the CPU load of Microsoft Outlook, change the counter path in the above example to this: 例如,为了获得Microsoft Outlook的CPU负载,请将上面示例中的计数器路径更改为此:

PdhAddCounter(query, TEXT("\\Process(OUTLOOK)\\% Processor Time"), 0, &counter);

If you have multiple instances of the same executable running, you may use indexes . 如果您正在运行同一个可执行文件的多个实例,则可以使用index This MSDN example is also very useful. 这个MSDN示例也非常有用。

In plain C, this is not possible, but since the question is also tagged "Windows": 在纯C语言中,这是不可能的,但是由于该问题也被标记为“ Windows”:

CPU usage is CPU time divided by real time. CPU使用率是CPU时间除以实时时间。 The GetThreadTimes and GetProcessTimes functions give you that information (among other features such as performance counters, which Joachim Pileborg mentioned above, but I think this one is probably easier). GetThreadTimesGetProcessTimes函数可以为您提供该信息(在其他功能(例如性能计数器)中,Joachim Pileborg曾提到过,但我认为这可能更容易)。

You probably also want to use CreateToolhelp32Snapshot first to know what processes and threads exist at all. 您可能还想先使用CreateToolhelp32Snapshot来了解所有存在的进程和线程。 You'll need to translate thread/process IDs to handles, but I guess that won't be a big hurdle (ie OpenProcess ). 您需要将线程/进程ID转换为句柄,但是我想这不会成为一个大障碍(即OpenProcess )。

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

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