简体   繁体   English

计算当前进程的CPU百分比

[英]Calculating the CPU percentage of the current process

I am using this code for calculate cpu usage of the process: 我正在使用此代码来计算进程的cpu用法:

using System;
using System.Timers;

public partial class Service1 : ServiceBase
{
    System.Timers.Timer CpuTimer = new System.Timers.Timer();
    public static TimeSpan LastCpuTime;
    public static DateTime LastCpuTimeChecked;

    protected override void OnStart(string[] args)
    {
        // Set up a timer to check the CPU every second or whatever.
        CpuTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        CpuTimer.Interval = 1000;
        CpuTimer.Enabled = true;
    }

    private static void OnTimedEvent(object Source, ElapsedEventArgs e)
    {
        // Get the 
        Int16 CpuPercentage = GetCpuPercentage(System.Diagnostics.Process.GetCurrentProcess());
    }

    private static Int16 GetCpuPercentage(System.Diagnostics.Process Process)
    {
        if (LastCpuTime == null)
        {
            // For the first run-through, we just need to start the clock.
            LastCpuTime = Process.TotalProcessorTime;
            LastCpuTimeChecked = DateTime.Now;
        }
        else
        {
            // How long since the last check?
            TimeSpan TimeElapsed = DateTime.Now - LastCpuTimeChecked;

            // How much CPU time was used?
            TimeSpan CpuTimePerProc = (Process.TotalProcessorTime - LastCpuTime);

            // Reset the clocks.
            LastCpuTime = Process.TotalProcessorTime;
            LastCpuTimeChecked = DateTime.Now;

            // Calculate the percentage of CPU time used by this process.
            Int16 CpuPercentage = (Int16)(
                (float)CpuTimePerProc.TotalMilliseconds /
                (float)TimeElapsed.TotalMilliseconds /
                Environment.ProcessorCount * 100
            );
            return CpuPercentage;
        }

        // Return something if we don't yet have enough data.
        return 0;
    }
}

But the result is very different from Task Manager (by 2-3 percent).Such a difference also with other processes too. 但是结果与任务管理器相差很大(2-3%),与其他流程也存在差异。

What could be the reason for this difference? 造成这种差异的原因可能是什么?

Aside from agreeing with Damien that what you're trying to do doesn't really seem to make sense, there are many reasons why you would get a value different from what is expected. 除了与Damien同意您试图做的事情似乎没有任何意义外,还有很多原因会使您获得与预期不同的价值。

  1. The accuracy of DateTime . DateTime的准确性。 This is already answered here: C# DateTime.Now precision . 这已经在这里得到回答: C#DateTime.Now precision To summarize, DateTime is not intended for accurate measurements -- it's just to present a representation of the current date and time. 总而言之, DateTime并非旨在进行准确的测量-只是表示当前日期和时间。
  2. The accuracy of Processor.TotalProcessorTime . Processor.TotalProcessorTime的精度。 This is mentioned here: How we can reduce the resolution of myProcess.TotalProcessorTime? 这里提到: 我们如何降低myProcess.TotalProcessorTime的分辨率? . To summarize, this is based on the clock interrupt frequency, which by default ticks 64 times a second. 总而言之,这基于时钟中断频率,默认情况下,时钟中断频率每秒滴答64次。

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

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