c# - ElapsedTicks、ElapsedMilliseconds、Elapsed.Milliseconds 和 Elapsed.TotalMilliseconds 之间的区别? (C#)

标签 c# performance .net-4.0 system.diagnostics stopwatch

我对这 4 个完全困惑。ElapsedMilliseconds (long)、ElapsedTicks (long)、Elapsed.TotalMilliseconds (double) 和 Elapsed.Milliseconds (int) 之间有什么区别?

我有一个函数

    {
        Stopwatch sw = new Stopwatch();

        sw.Start();
        MyTimeConsumingAction();
        sw.Stop();

        sw.//what?
    }

如何从 Stopwatch 对象的 elapsed 属性中获取我长时间运行的进程消耗的正确时间(以毫秒为单位)?

编辑:我尝试了 msdn 文档,但那里没有任何详细信息..

最佳答案

Elapsed.TotalMilliseconds (double) returns the total number of whole and fractional milliseconds elapsed since inception

例如停在 1.23456 秒的秒表将在此属性中返回 1234.56。请参阅 MSDN 上的 TimeSpan.TotalMilliseconds

Elapsed.Milliseconds (int) returns the number of whole milliseconds in the current second

例如秒表在 1.234 秒时会在此属性中返回 234。见 TimeSpan.Milliseconds

ElapsedTicks (long) returns the ticks since start of the stopwatch.

在原始问题的上下文中,与 Stopwatch 类有关,ElapsedTicks 是经过的滴答数。滴答以 Stopwatch.Frequency 的速率发生,因此,要计算经过的秒数,请计算:numSeconds = stopwatch.ElapsedTicks/Stopwatch.Frequency

旧答案将滴答定义为 100 纳秒周期的数量,这在 DateTime 类的上下文中是正确的,但在 Stopwatch 类的上下文中是不正确的。请参阅 MSDN 上的 Stopwatch.ElapsedTicks

ElapsedMilliseconds returns a rounded number to the nearest full millisecond, so this might lack precision Elapsed.TotalMilliseconds property can give.

Elapsed.TotalMilliseconds 是一个 double 可以将执行时间返回到部分毫秒,而 ElapsedMillisecondsInt64 .例如在此属性中,0.0007 毫秒的秒表将返回 0,或 1234.56 毫秒将返回 1234。因此,为了精确起见,请始终使用 Elapsed.TotalMilliseconds

有关说明,请参阅 Stopwatch.ElapsedMilliseconds on MSDN

关于c# - ElapsedTicks、ElapsedMilliseconds、Elapsed.Milliseconds 和 Elapsed.TotalMilliseconds 之间的区别? (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8894425/

相关文章:

c# - c#中类的泛型调用

jquery - 获取文本框文本,javascript已更改

r - 分支预测如何影响 R 中的性能?

c# - ConcurrentDictionary.GetOrAdd 始终执行委托(delegate)方法

c# - 两个字符串数组的完全外连接

c# - 如何使div可见和不可见

c# - 按数字然后按字母对数组列表进行排序

.net - 我可以在 .net 4 上运行 asp.net mvc 1 吗?

c# - 如何停止 C# 中的线程?

android - 在运行时使用 MVVM 中的数据添加绑定(bind) View