how to set timer for calculate execution time

ratty picture ratty · Apr 6, 2010 · Viewed 19.5k times · Source

i like to set timer for calculating execution time in c# for particular process in my execution. how can i do this

Answer

Jon Skeet picture Jon Skeet · Apr 6, 2010

You don't generally use a timer for this - you use a Stopwatch.

Stopwatch sw = Stopwatch.StartNew();
// Do work
sw.Stop();
TimeSpan elapsedTime = sw.Elapsed;

If you're performing benchmarking of something relatively fast, it's worth doing it many, many times so that the time taken is significant (I usually go for 5-30 seconds). That's not always feasible, admittedly - and there are many more subtleties which affect real world performance (such as cache hits/misses) which micro-benchmarking often misses out on.

Basically, be careful - but Stopwatch is probably the best starting point in many cases.