How do you convert Stopwatch ticks to nanoseconds, milliseconds and seconds?

后端 未结 6 2024
悲哀的现实
悲哀的现实 2020-12-23 09:01

This is a very basic question...quite embarassing, but here goes:

I have a Stopwatch block in C# code. I determine the elapsed time in ticks and then want to conver

6条回答
  •  青春惊慌失措
    2020-12-23 09:53

    Stopwatch.Elapsed is a TimeSpan, so you can do myStopwatch.Elapsed.TotalMilliseconds, myStopwatch.Elapsed.TotalSeconds, etc.

    // Create new stopwatch
    Stopwatch stopwatch = new Stopwatch();
    
    // Begin timing
    stopwatch.Start();
    
    // Do something
    for (int i = 0; i < 1000; i++)
    {
        Thread.Sleep(1);
    }
    
    // Stop timing
    stopwatch.Stop();
    
    // Write result
    Console.WriteLine("Time elapsed (s): {0}", stopwatch.Elapsed.TotalSeconds);
    Console.WriteLine("Time elapsed (ms): {0}", stopwatch.Elapsed.TotalMilliseconds);
    Console.WriteLine("Time elapsed (ns): {0}", stopwatch.Elapsed.TotalMilliseconds * 1000000);
    

    Output:

    Time elapsed (s): 2.4976622
    Time elapsed (ms): 2497.6622
    Time elapsed (ns): 2497662200
    

    Note that stopwatch.ElapsedMilliseconds returns a long and is thus only precise up to the millisecond, while stopwatch.Elapsed.TotalMilliseconds returns a double and has the same precision as stopwatch.ElapsedTicks, except it's easier to use. ILSpy shows that TimeSpan.TotalMilliseconds is computed using ticks anyway.

提交回复
热议问题