Stopwatch ticks are different from DateTime.Ticks

Stopwatch ticks are different from DateTime.Ticks

In C#/.NET the System.Diagnostic.Stopwatch class can be used for more precise timing than when using System.DateTime. Until recently, despite many years of using .NET, I hadn’t used Stopwatch; DateTime was precise enough for timing web applications or timing over thousands of iterations. I didn’t actually need to use it now, but I decided to give it a try at last, and then got caught out by Stopwatch ticks not being what I expected.

The gist of it is that there are exactly 10,000,000 (10 million) DateTime ticks in 1 second, but the number of Stopwatch ticks per second is machine dependent. You need to call the static property Stopwatch.Frequency to get the number of Stopwatch ticks per second for the machine.

Read more on James Michael Hare’s blog post: http://geekswithblogs.net/BlackRabbitCoder/archive/2012/01/12/c.net-little-pitfalls-stopwatch-ticks-are-not-timespan-ticks.aspx

Or on the Microsoft docs: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch.elapsedticks?view=netframework-4.8#remarks

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.