如何将秒表滴答转换为毫微秒,毫秒和秒?

这是一个非常基本的问题…很尴尬,但是这里有:

我有一个C#代码中的秒表块。 我用滴答确定stream逝的时间,然后想转换为ns,ms,s。 我知道,频率是由秒表类提供的,而且是转换所必需的。

谢谢

Stopwatch.Elapsed是一个TimeSpan ,所以你可以做myStopwatch.Elapsed.TotalMillisecondsmyStopwatch.Elapsed.TotalSeconds

 // 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); 

输出:

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

请注意stopwatch.ElapsedMilliseconds返回一个long ,因此只能精确到毫秒,而stopwatch.Elapsed.TotalMilliseconds返回一个double具有与 stopwatch.ElapsedTicks 相同的精度 ,但使用起来更容易。 ILSpy显示TimeSpan.TotalMilliseconds是使用ticks来计算的。

根据MSDN ,频率告诉你每秒的滴答数。 因此:

 Stopwatch sw = new Stopwatch(); // ... double ticks = sw.ElapsedTicks; double seconds = ticks / Stopwatch.Frequency; double milliseconds = (ticks / Stopwatch.Frequency) * 1000; double nanoseconds = (ticks / Stopwatch.Frequency) * 1000000000; 

Stopwatch.Frequency给你蜱/秒。

所以,如果你有蜱虫,你可以按频率划分得到秒:

 long ticks = sw.ElapsedTicks; double ns = 1000000000.0 * (double)ticks / Stopwatch.Frequency; double ms = ns / 1000000.0; double s = ms / 1000; 

例如,你可以这样做:

 static void Main() { Stopwatch sw = new Stopwatch(); sw.Start(); System.Threading.Thread.Sleep(3456); sw.Stop(); long ticks = sw.ElapsedTicks; double ns = 1000000000.0 * (double)ticks / Stopwatch.Frequency; double ms = ns / 1000000.0; double s = ms / 1000; Console.WriteLine("{0}, {1}, {2}", ns, ms, s); Console.ReadKey(); } 

在我的系统上打印:

 3455650175.58075, 3455.65017558075, 3.45565017558075 

使用这个类:

 public static class Utility { public static long ElapsedNanoSeconds(this Stopwatch watch) { return watch.ElapsedTicks * 1000000000 / Stopwatch.Frequency; } public static long ElapsedMicroSeconds(this Stopwatch watch) { return watch.ElapsedTicks * 1000000 / Stopwatch.Frequency; } } 

那么你可以像这样获得经过的纳秒/微秒:

 var stopwatch = Stopwatch.StartNew(); //... measured code part Console.WriteLine(stopwatch.ElapsedNanoSeconds()); // OR Console.WriteLine(stopwatch.ElapsedMicroSeconds()); 

对于毫秒,您可以使用Stopwatch的ElapsedMilliseconds()方法。

从MSDN文档 :

使用Frequency和IsHighResolution字段来确定秒表计时实施的精度和分辨率。

 long frequency = Stopwatch.Frequency; Console.WriteLine(" Timer frequency in ticks per second = {0}", frequency); long nanosecPerTick = (1000L*1000L*1000L) / frequency; Console.WriteLine(" Timer is accurate within {0} nanoseconds", nanosecPerTick); 

使用Elapsed属性:

 stopwatch.Elapsed.TotalMilliseconds 

如果从秒表中获得已用时间,则有时间对象的属性可以获得秒,磨等。

 TimeSpan ts = stopWatch.Elapsed; int seconds = ts.FromSeconds; int mill = ts.FromMiliseconds;