Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

High resolution timer in .NET

I'd like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs that I haven't yet found.

like image 375
Mats Fredriksson Avatar asked Oct 02 '08 15:10

Mats Fredriksson


People also ask

What is system's high resolution time?

4 High Resolution Time This specification defines an interface that provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.

What is the resolution of a timer?

In other words, a difference in the second digit to the right of the decimal point is the smallest difference between two measurements that can be displayed on this timer. But the smallest difference between two measured values is the resolution of the timer.

What is high resolution timer in Linux?

The High Resolution Timers system allows a user space program to be wake up from a timer event with better accuracy, when using the POSIX timer APIs. Without this system, the best accuracy that can be obtained for timer events is 1 jiffy. This depends on the setting of HZ in the kernel.

How accurate is the stopwatch class?

Stopwatch class does accurately measure time elapsed, but the way that the ElapsedTicks method works has led some people to the conclusion that it is not accurate, when they really just have a logic error in their code.


1 Answers

Here is a sample bit of code to time an operation:

Dim sw As New Stopwatch() sw.Start() //Insert Code To Time sw.Stop() Dim ms As Long = sw.ElapsedMilliseconds Console.WriteLine("Total Seconds Elapsed: " & ms / 1000) 

EDIT:

And the neat thing is that it can resume as well.

Stopwatch sw = new Stopwatch(); foreach(MyStuff stuff in _listOfMyStuff) {     sw.Start();     stuff.DoCoolCalculation();     sw.Stop(); } Console.WriteLine("Total calculation time: {0}", sw.Elapsed); 

The System.Diagnostics.Stopwatch class will use a high-resolution counter if one is available on your system.

like image 106
5 revs, 5 users 47% Avatar answered Sep 29 '22 22:09

5 revs, 5 users 47%