7

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

ratty
  • 13,216
  • 29
  • 75
  • 108

3 Answers3

37

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
10

You can use System.Diagnostics.Stopwatch to do what you want.

Adrian Fâciu
  • 12,414
  • 3
  • 53
  • 68
0

You can use a Timer and attach an action to the Elapsed event. For instance you can abort your thread... hmm if you are not affraid of the consequences... Actually you can do that if you want to set a timeout to your process for instance.

If it's just for monitoring, Stopwatch just fits your needs

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
pierroz
  • 7,653
  • 9
  • 48
  • 60
  • Interesting read on aborting threads: http://blogs.msdn.com/ericlippert/archive/2010/02/22/should-i-specify-a-timeout.aspx and http://blogs.msdn.com/ericlippert/archive/2010/02/25/careful-with-that-axe-part-two-what-about-exceptions.aspx – R. Martinho Fernandes Apr 06 '10 at 07:03