How To: Measure execution time in C#





2.00/5 (1 vote)
Here is a useful generic class you can directly use in your project.public class Timer{ public static readonly bool IsHighPerformance; [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter(out long lpPerformanceCount); //Retrieves the current...
Here is a useful generic class you can directly use in your project.
public class Timer
{
public static readonly bool IsHighPerformance;
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
//Retrieves the current value of the high-resolution performance counter.
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
//Retrieves the frequency of the high-resolution performance counter, if one exists.
//The frequency cannot change while the system is running.
private long m_startTime;
private long m_stopTime;
private static long m_freq;
static Timer()
{
try
{
IsHighPerformance = QueryPerformanceFrequency(out m_freq);
}
catch (Exception)
{
IsHighPerformance = false;
}
}
public Timer()
{
m_startTime = 0;
m_stopTime = 0;
}
///
/// Start the timer
///
public void Start()
{
// let the waiting threads do their work
Thread.Sleep(0);
if (IsHighPerformance)
{
QueryPerformanceCounter(out m_startTime);
}
else
{
m_startTime = DateTime.Now.Ticks;
}
}
///
/// Stop the timer
///
public void Stop()
{
if (IsHighPerformance)
{
QueryPerformanceCounter(out m_stopTime);
}
else
{
m_stopTime = DateTime.Now.Ticks;
}
}
///
/// Returns the duration of the timer (in fraction of seconds)
///
public double DurationSeconds
{
get
{
if (IsHighPerformance)
{
return (double)(m_stopTime - m_startTime) / (double)m_freq;
}
else
{
TimeSpan span = (new DateTime(m_stopTime)) - (new DateTime(m_startTime));
return span.TotalSeconds;
}
}
}
public double DurationMilliseconds
{
get
{
if (IsHighPerformance)
{
return (double)(m_stopTime - m_startTime) / (double)m_freq;
}
else
{
TimeSpan span = (new DateTime(m_stopTime)) - (new DateTime(m_startTime));
return span.TotalMilliseconds;
}
}
}
}
//////demo
//static void Main() {
//Timer timer = new Timer();
//timer.Start();
// do something here
//timer.Stop();
//Console.WriteLine(timer.DurationSeconds);
//}
//////////the second class time of without using the system function
class Timing2
{
TimeSpan startingTime;
TimeSpan duration;
public Timing2()
{
startingTime = new TimeSpan(0);
duration = new TimeSpan(0);
}
public void StopTime()
{
duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime);
}
public void startTime()
{
GC.Collect();
GC.WaitForPendingFinalizers();
startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
}
public TimeSpan Result()
{
return duration;
}
}