Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display accurate times for testing performance numbers in C#

I want to test the speed of an algorithm, what DateTime overload will give me the most precise time? (I still need day/month/year/seconds but then I want milliseconds also).

like image 918
Blankman Avatar asked Dec 03 '22 15:12

Blankman


2 Answers

Try using System.Diagnostics.Stopwatch to do this:

http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

like image 181
lexx Avatar answered May 17 '23 23:05

lexx


Others have mentioned Stopwatch, which is indeed a good idea. However, I have a different approach: I try to measure the algorithm for long enough that the normal system timer resolution would be adequate. (I generally still use Stopwatch, as it's the right type for the job, but it wouldn't matter.) For example, in my recent IO testing I only bother to report seconds, because my tests take minutes (sometimes half an hour) to run. At that point, milliseconds are inappropriate, because they'd be lost in the noise of other processes interrupting etc.

It's not always possible to run tests for that long of course, but it's a nice thing to do where you can. For shorter tests, I'd be wary of benchmarks which take less than about 5 seconds... a brief bit of activity from another process can have a disproportionate effect.

Another thing to consider - measure CPU time instead of wall time:

   [DllImport("kernel32.dll")]
   [return: MarshalAs(UnmanagedType.Bool)]
   static extern bool GetProcessTimes(IntPtr hProcess, 
      out FILETIME lpCreationTime, 
      out FILETIME lpExitTime,
      out ulong lpKernelTime,
      out ulong lpUserTime);

   static ulong GetTime(Process process)
   {
       FILETIME lpCreationTime, lpExitTime;
       ulong lpKernelTime, lpUserTime;

       GetProcessTimes(process.Handle, out lpCreationTime,
                       out lpExitTime, out lpKernelTime, out lpUserTime);

       return lpKernelTime + lpUserTime;
   }
like image 35
Jon Skeet Avatar answered May 18 '23 00:05

Jon Skeet