Wednesday, January 16, 2008

Best way to find execution time of a part of code

Instead of using DateTime Object to find out the execution time (which gives only milliseconds of difference) use QueryPerformanceCounter and QueryPerformanceFrequency Win32 API menthods.

QueryPerformanceCounter(), queries the actual value of the high-resolution performance counter at any point. The second function, QueryPerformanceFrequency(), will return the number of counts per second that the high-resolution counter performs. therefore execution time = (start QueryPerformanceCounter - stop QueryPerformanceCounter)/ QueryPerformanceFrequency


using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
internal class HiPerfTimer
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);

[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(
out long lpFrequency);

private long startTime, stopTime;
private long freq;

// Constructor

public HiPerfTimer()
{
startTime = 0;
stopTime = 0;

if (QueryPerformanceFrequency(out freq) == false)
{
// high-performance counter not supported

throw new Win32Exception();
}
}

// Start the timer

public void Start()
{
// lets do the waiting threads there work

Thread.Sleep(0);

QueryPerformanceCounter(out startTime);
}

// Stop the timer

public void Stop()
{
QueryPerformanceCounter(out stopTime);
}

// Returns the duration of the timer (in seconds)

public double Duration
{
get
{
return (double)(stopTime - startTime) / (double) freq;
}
}
}
}

This class is very simple to use. Just create an instance of HiPerfTimer, call Start() to start timing and call Stop() to stop timing. To retrieve the elapsed time, just call the Duration() function and you will get the elapsed time.

The following sample should explain that.

HiPerfTimer pt = new HiPerfTimer(); // create a new PerfTimer object

pt.Start(); // start the timer

Console.WriteLine("Test\n"); // the code to be timed

pt.Stop(); // stop the timer

Console.WriteLine("Duration: {0} sec\n",
pt.Duration); // print the duration of the timed code

No comments: