gpt4 book ai didi

c# - 使用 Timer 为 C# 代码计时

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:11:41 24 4
gpt4 key购买 nike

尽管从算法分析和 Big-Oh 的角度检查代码的性能是件好事!我想看看代码在我的电脑上执行需要多少时间。我已经将一个 List 初始化为 9999count 并从中删除了偶数元素。遗憾的是,执行此操作的时间跨度似乎是 0:0:0。对结果感到惊讶,我计算执行时间的方式肯定有问题。 有人可以帮我正确计时代码吗?

        IList<int> source = new List<int>(100);
for (int i = 0; i < 9999; i++)
{
source.Add(i);
}

TimeSpan startTime, duration;
startTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;

RemoveEven(ref source);
duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startTime);

Console.WriteLine(duration.Milliseconds);
Console.Read();

最佳答案

最适合使用的东西是 Stopwatch - 任何涉及 TimeSpan 的东西都远远不够对此有足够的精度:

var watch = Stopwatch.StartNew();
// something to time
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);

但是,现代 CPU 速度非常快,如果它可以在那个时候删除它们,我也不会感到惊讶。通常,对于计时,您需要多次重复操作才能获得合理的测量。

另外:RemoveEven(ref source) 中的 ref 几乎肯定不需要。

关于c# - 使用 Timer 为 C# 代码计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com