Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact time measurement for performance testing [duplicate]

What is the most exact way of seeing how long something, for example a method call, took in code?

The easiest and quickest I would guess is this:

DateTime start = DateTime.Now; {     // Do some work } TimeSpan timeItTook = DateTime.Now - start; 

But how exact is this? Are there better ways?

like image 226
Svish Avatar asked Jun 09 '09 10:06

Svish


2 Answers

A better way is to use the Stopwatch class:

using System.Diagnostics; // ...  Stopwatch sw = new Stopwatch();  sw.Start();  // ...  sw.Stop();  Console.WriteLine("Elapsed={0}",sw.Elapsed); 
like image 77
Philippe Leybaert Avatar answered Sep 30 '22 21:09

Philippe Leybaert


As others have said, Stopwatch is a good class to use here. You can wrap it in a helpful method:

public static TimeSpan Time(Action action) {     Stopwatch stopwatch = Stopwatch.StartNew();     action();     stopwatch.Stop();     return stopwatch.Elapsed; } 

(Note the use of Stopwatch.StartNew(). I prefer this to creating a Stopwatch and then calling Start() in terms of simplicity.) Obviously this incurs the hit of invoking a delegate, but in the vast majority of cases that won't be relevant. You'd then write:

TimeSpan time = StopwatchUtil.Time(() => {     // Do some work }); 

You could even make an ITimer interface for this, with implementations of StopwatchTimer, CpuTimer etc where available.

like image 37
Jon Skeet Avatar answered Sep 30 '22 20:09

Jon Skeet