aikidos
aikidos

Reputation: 1

Calculating the CPU percentage of the current process

I am using this code for calculate cpu usage of the process:

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.

What could be the reason for this difference?

Upvotes: 0

Views: 1830

Answers (1)

Lunyx
Lunyx

Reputation: 3284

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.

  1. The accuracy of DateTime. This is already answered here: 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.
  2. The accuracy of Processor.TotalProcessorTime. This is mentioned here: How we can reduce the resolution of myProcess.TotalProcessorTime?. To summarize, this is based on the clock interrupt frequency, which by default ticks 64 times a second.

Upvotes: 1

Related Questions