为什么我的ElapsedMilliseconds总是为零?

时间:2016-04-10 05:35:35

标签: c# .net performance data-structures

所以我试图测量我创建的哈希集的性能与List以及下面的代码块中相同元素的性能

        Stopwatch Watch = new Stopwatch();
        long tList = 0, tHset = 0; // ms
        foreach ( string Str in Copy )
        {
            // measure time to look up string in ordinary list
            Watch.Start();
            if ( ListVersion.Contains(Str) ) { }
            Watch.Stop();
            tList += Watch.ElapsedMilliseconds;
            // now measure time to look up same string in my hash set
            Watch.Reset();
            Watch.Start();
            if ( this.Contains(Str) ) { }
            Watch.Stop();
            tHset += Watch.ElapsedMilliseconds;
            Watch.Reset();
        }
        int n = Copy.Count;
        Console.WriteLine("Average milliseconds to look up in List: {0}", tList / n);
        Console.WriteLine("Average milliseconds to look up in hashset: {0}", tHset / n);

两者都输出0。知道为什么会这样吗?相关文档:https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx

1 个答案:

答案 0 :(得分:0)

您可以保持代码不变,而不是:

Watch.ElapsedMilliseconds

你这样做:

Watch.Elapsed.TotalMilliseconds

这样你将得到毫秒的小数部分