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?