如何将秒表刻度转换为纳秒,毫秒和秒? [英] How do you convert Stopwatch ticks to nanoseconds, milliseconds and seconds?

查看:131
本文介绍了如何将秒表刻度转换为纳秒,毫秒和秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有一个C#代码的秒表块.我以秒为单位确定经过的时间,然后想要转换为ns,ms,s.我知道频率是由秒表类提供的,并且它是转换所必需的.

I have a Stopwatch block in C# code. I determine the elapsed time in ticks and then want to convert to ns, ms, s. I know that the Frequency is provided by the Stopwatch class and that it is required for conversion.

谢谢

推荐答案

Stopwatch.经过的是

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

输出:

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

请注意秒表.ElapsedMilliseconds 返回一个 long ,因此精确到毫秒,而 stopwatch.Elapsed.TotalMilliseconds 返回 double ,并且具有与 stopwatch.ElapsedTicks 相同的精度,但它更易于使用.ILSpy显示 TimeSpan.TotalMilliseconds 始终使用刻度来计算.

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.

这篇关于如何将秒表刻度转换为纳秒,毫秒和秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆