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);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
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;
}
public void Start()
{
Thread.Sleep(0);
if (IsHighPerformance)
{
QueryPerformanceCounter(out m_startTime);
}
else
{
m_startTime = DateTime.Now.Ticks;
}
}
public void Stop()
{
if (IsHighPerformance)
{
QueryPerformanceCounter(out m_stopTime);
}
else
{
m_stopTime = DateTime.Now.Ticks;
}
}
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;
}
}
}
}
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;
}
}