获取Windows中空闲进程的总CPU时间类似于任务管理器 [英] Obtain Total CPU Time of Idle Process in Windows similar to Task Manager

查看:27
本文介绍了获取Windows中空闲进程的总CPU时间类似于任务管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个大型应用程序,想了解两个时间点之间 CPU 的负载情况.我不仅对自己的流程感兴趣,还对所有流程感兴趣.

I am working on a large application and want to get an idea of how loaded the CPU was between two points in time. I am not just interested in my own process, but all processes.

我的想法是获取两个时间段之间空闲进程的总 CPU 时间.然后将该值与实时差异进行比较.然后就可以计算在空闲进程上花费的平均 CPU 时间百分比,从而计算出实际进程上花费的平均 CPU 百分比.

My idea is to get the Total CPU Time of the Idle Process between two time periods. Then compare that value to the real time difference. It is then possible to calculate the average % CPU Time spent on the Idle process, and hence the average % CPU spent on actual processes.

例如:

  • 实时采样:2012/07/30 13:56:1 和 2012/07/30 13:56:21
  • 空闲进程总 CPU 时间样本:56:23:10 和 56:23:15
  • 实时差异:20 秒
  • 空闲进程总 CPU 时间的差异:5s
  • 空闲进程中的平均 CPU 时间百分比:25%
  • 实际进程中的平均 CPU 时间百分比:75%

为了尽可能减少性能影响,我只想取两个样本.一个在开头,一个在结尾.

In order to have as little performance impact as possible, I only want to take two samples. One at the beginning and one at the end.

我也不想为了计算总CPU负载而查看其他进程,只查看空闲进程.(例如我不想计算其他进程的总 CPU 时间的总和)

I also do not want to look at other processes in order to calculate the total CPU load, only the Idle Process. (For instance I don't want to calculate the sum of Total CPU Time of other processes)

我尝试使用 Kernel32.dll OpenProcess.但显然您无法访问空闲进程.它抛出一个 ERROR_ACCESS_DENIED 异常.

I have tried to use the Kernel32.dll OpenProcess. But apperantly you cannot access the Idle Process. It throws an ERROR_ACCESS_DENIED exception.

这一定是可能的,因为任务管理器会显示空闲进程的总 CPU 时间.

This must be possible as Task Manager displays the Total CPU Time of the Idle Process.

注意:我对进程的瞬时百分比 CPU 时间不感兴趣.只有总 CPU 时间,以便稍后计算平均值.

推荐答案

您可能正在寻找这样的东西:

You are probably looking for something like this:

static Program
{
    private static PerformanceCounter cpuCounter = new PerformanceCounter() { 
        CategoryName = "Processor", 
        CounterName = "% Processor Time", 
        InstanceName = "_Total" };

    static void Main()
    {
        cpuCounter.NextValue();
        // Do your processing here.
        float totalCpuUsagePercentage = cpuCounter.NextValue();
    }
}

totalCpuUsagePercentage 将包含自上次 cpuCounter.NextValue() 以来的总负载百分比.

totalCpuUsagePercentage will then contain the total load in percentage since the last cpuCounter.NextValue().

如果您不想要百分比,您可以使用 CounterName = "Processor Time" 代替.

If you don't want the percentage you can use CounterName = "Processor Time" instead.

希望这能帮助您完成任务.

Hope that this will help you on your quest.

这篇关于获取Windows中空闲进程的总CPU时间类似于任务管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆