Sunday, April 23, 2006

Exact measurement of performance in Dot.Net

Utils.PerfMeter - unpretentious class for exact gauging performance in Dot.Net.
Measures much more precisely than Environment.TickCount. Environment.TickCount has accuracy 10 milisecond,
that for measurement of short sites does not approach.
Use QueryPerformanceCounter allows to provide very high accuracy.
To use so:
//Define variable
PerfMeter timer = new PerfMeter();

timer.Start();

// A code for test.......

//Print result to console
Console.WriteLine("Execution time in seconds: {0:### ### ##0.0000}"
timer.End());

//You can to use one variable several times

Class code:
using System;
using System.Runtime.InteropServices;

namespace Utils
{

/*This structure allows to count up speed of performance of a code one of the most exact of ways. Actually calculations are made in steps of the processor, and then translated in miliseconds (the decimal part is shares of second).
*/

  public struct PerfMeter
  {
  Int64 _start;

  /// Start timer
  public void Start()
  {
  _start = 0;
  QueryPerformanceCounter(ref _start);
  }
  /// Finished calculation time executions and returns time in seconds.

  /*Return: Time in seconds spent for performance of a site of a code. The   decimal part reflects shares of second */
  public float End()
  {
  Int64 end = 0;
  QueryPerformanceCounter(ref end);

  Int64 frequency = 0;
  QueryPerformanceFrequency(ref Frequency);
  return (((float)(end - _start) /(float)freq));
  }

  [DllImport("Kernel32.dll")]
  static extern bool QueryPerformanceCounter(ref Int64 performanceCount);

  [DllImport("Kernel32.dll")]
  static extern bool QueryPerformanceFrequency(ref Int64 frequency);
  }
}

No comments: