Friday May 6th

Thursday May 5th

Measuring Time More Accurately

How to accurately measure how much time has passed while performing some operation? Use the Stopwatch class. Here is how.

3 comments

Easy, handy, I like it. thanks

This is exactly what I was looking for, even before I started looking for it ;) Great kick, thanks!

Hey Thanks All,

I tried Stopwatch .NET 2.0 but its not found, or i think i am missing some reference.
So i used the following program, and it worked fine.

using System;
using System.Runtime.InteropServices;
namespace TestSqlTimeOutException_Soundar
{
public sealed class StopWatch
{
[DllImport("kernel32.dll")]
extern static int QueryPerformanceCounter(ref long x);

[DllImport("kernel32.dll")]
extern static int QueryPerformanceFrequency(ref long x);


public StopWatch()
{
Frequency = GetFrequency();
Reset();
}

public void Reset()
{
StartTime = GetValue();
}

public long Peek()
{
return (long)(((GetValue() - StartTime)
/ (double)Frequency) * 10000);
}

private long GetValue()
{
long ret = 0;
if (QueryPerformanceCounter(ref ret) == 0)
throw new NotSupportedException(
"Error while querying "
+ "the high-resolution performance counter.");
return ret;
}

private long GetFrequency()
{
long ret = 0;
if (QueryPerformanceFrequency(ref ret) == 0)
throw new NotSupportedException(
"Error while querying "
+ "the performance counter frequency.");
return ret;
}

private long StartTime
{
get
{
return m_StartTime;
}
set
{
m_StartTime = value;
}
}

private long Frequency
{
get
{
return m_Frequency;
}
set
{
m_Frequency = value;
}
}



#region -- Private Variables --

/// <summary>
/// Holds the value of the StartTime property.
/// </summary>
private long m_StartTime;

/// <summary>
/// Holds the value of the Frequency property.
/// </summary>
private long m_Frequency;

#endregion

}
}

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network