How to get accurate ticks from a timer (high‑resolution timer) in C#

1 Answer

0 votes
using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        var sw = Stopwatch.StartNew();

        // Do some work
        for (int i = 0; i < 1_000_000; i++) { }

        sw.Stop();

        Console.WriteLine("Elapsed ticks: " + sw.ElapsedTicks);
        Console.WriteLine("Elapsed ms: " + sw.Elapsed.TotalMilliseconds);
        Console.WriteLine("Timer frequency: " + Stopwatch.Frequency);
        Console.WriteLine("Is high resolution: " + Stopwatch.IsHighResolution);
        
        // Convert ticks to real time
        double seconds = (double)sw.ElapsedTicks / Stopwatch.Frequency;
        double microseconds = seconds * 1_000_000;
        double nanoseconds = seconds * 1_000_000_000;
        
        Console.WriteLine("Seconds: " + seconds);
        Console.WriteLine("Microseconds: " + microseconds);
        Console.WriteLine("Nanoseconds: " + nanoseconds);
    }
}



/*
run:

Elapsed ticks: 10286
Elapsed ms: 1.0286
Timer frequency: 10000000
Is high resolution: True
Seconds: 0.0010286
Microseconds: 1028.6
Nanoseconds: 1028600

*/

 



answered May 8 by avibootz
...