Using a more accurate approach to Timing
As of .NET 2.0 there is a new class called StopWatch in System.Diagnostics. It is very easy to use. I just found it, while playing around with my Md5 optimization "project".
For all of you that can't upgrade to Framework 2.0 yet - here is the implementation I used to time my md5 algos. It is loosely based on the high performance timer Daniel Strigl posted on codeproject. I enhanced it a little bit in order to be able to use it running Mono on Linux. In that case it defaults to DateTime.Tick accuracy.
C#:
- using System;
- using System.Runtime.InteropServices;
- using System.Threading;
- namespace Md5Optimized
- {
- public class PerformanceTimer
- {
- 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 PerformanceTimer()
- {
- try
- {
- IsHighPerformance =
- QueryPerformanceFrequency(out m_freq);
- }
- catch (Exception)
- {
- IsHighPerformance = false;
- }
- }
- public PerformanceTimer()
- {
- m_startTime = 0;
- m_stopTime = 0;
- }
- /// <summary>
- /// Start the timer
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// Stop the timer
- /// </summary>
- public void Stop()
- {
- if (IsHighPerformance)
- {
- QueryPerformanceCounter(out m_stopTime);
- }
- else
- {
- m_stopTime = DateTime.Now.Ticks;
- }
- }
- /// <summary>
- /// Returns the duration of the timer
- /// (in fraction of seconds)
- /// </summary>
- public double DurationSeconds
- {
- get
- {
- if (IsHighPerformance)
- {
- return (double)(m_stopTime - m_startTime) /
- (double)m_freq;
- }
- else
- {
- TimeSpan span =
- return span.TotalSeconds;
- }
- }
- }
- }
- }
Please keep in mind that this class is a quick hack. It works...
but only if used correctly.

really good stuff
it works fine to me !
Comment on March 12, 2007 @ 17:39:52
hey it looks good! I’m just wondering why you sleep before starting the timer. Is that to make the timer a little more accurate for really short times by making sure the current thread can do some work before being scheduled out?
Comment on May 2, 2007 @ 14:38:33
Hey Ben,
the Thread.Sleep(0); is there to make it less likely that the to-be-timed thread will be put to suspended state by the thread-scheduler during the timing, because already waiting threads will get the chance to do their work before the timing starts. To quote the documentation on Thread.Sleep:
Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute.
Therefore your conclusion is absolutely correct. The timing will be more accurate since by average the thread will be running with less suspended time. However: ideally your computer should not be occupied at all with other conflicting tasks during execution of the to-be-optimized code anyway.
Thanks,
Tobi
Comment on May 6, 2007 @ 23:56:52
hi,
i am the new learner for c#. after i copying your program to C# console application, an error occru
it write that
doesnt contain a static “main” method suitable for entry point
.What does it mean??
Thank you for help
Comment on June 11, 2007 @ 10:38:12
Hi Carrie,
the file you downloaded is not a complete C# program, it just represents a class that helps you time a program. but you have to write a complete c# program for it to work.
You need to write something like this in a second file and compile:
class Example {
static void Main() {
PerformanceTimer timer = new PerformanceTimer();
timer.Start();
// do something here
timer.Stop();
Console.WriteLine(timer.DurationSeconds);
}
}
Please do start with some basic tutorials on C#.
Pick a choose
Comment on June 12, 2007 @ 20:16:13
In your static constructor add calls to Start() and Stop() methods.
This will ensure that the methods have been ‘jitted’ before first call…
Something like:
PerformanceTimer pt = new PerformanceTimer();
pt.Start();
pt.Stop();
pt = null;
Comment on January 17, 2008 @ 16:01:40
Hi Tobias,
Very nice. But I have a question.
I would like to create an Event that triggers every so many milliseconds. I only need 1ms accuracy at the most.
Now I’ve tried the easy way with the Clock method. But not matter what I try for the Interval prop, the results are not reliable (1ms Interval gets me 14,15,16ms between the printed time in my log file – 20ms gives me 30,31,32ms).
Your methods is more accurate but only used as a stopwatch. Is there a way to generate an Event using this method? So I can do something simple (write a line to a log file) every so many ms?
Thanks!
Marco
Comment on January 28, 2009 @ 16:57:40
Hi Marco,
unfortuantelly, I don’t know any high res timer that does not require a hot loop. And therefore would only work correctly on a dual cpu system (and 100%ing one of the cpus.)
Not too optimal, is it? And I don’t know how accurate Thread.Sleep(1) would be…
And please be aware of the fact that writing to a log on disk will have a natural delay as well, since hard disks have a seek time of _several_ ms – and therefore might be the real reason why you don’t see the expected interval.
Cheers,
Tobi
Comment on January 29, 2009 @ 10:49:04
hi. its nice work. I want to create two threads and with the help of timer class
i want to throw these threads on different times. i read a lot of materials but didn’t found anything which meets my requirement.
Thank for your help and positive reply
Comment on May 24, 2009 @ 23:03:22