How to set a timer to calculate runtime

I like to set a timer to calculate the runtime in C # for a specific process in my execution. How can i do this

+7
c # execution
source share
3 answers

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

+10
source share

Usually a timer is not used for this - you are using Stopwatch .

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

If you benchmark something relatively quickly, you should do it many, many times so that the time is significant (I usually go for 5-30 seconds). This is not always feasible, admittedly, and there are many more subtleties that affect real-world performance (like cache hits / skips) that often skip micro-benchmarking.

In principle, be careful, but Stopwatch is probably the best starting point in many cases.

+37
source share

You can use the Timer and apply the action to the Expired . For example, you can interrupt your thread ... hmm, if you are not afraid of the consequences ... In fact, you can do this if you want, for example, to set a timeout for your process.

If it's just for monitoring, the stopwatch just fits your needs.

0
source share

All Articles