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).
Try using System.Diagnostics.Stopwatch to do this:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With