使用Timer计时C#代码 [英] Timing C# code using Timer

查看:82
本文介绍了使用Timer计时C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使从算法分析和Big-Oh方面检查代码性能还是不错的!表示法我想看看在我的PC上执行代码要花多少钱.我已经将List初始化为9999count,甚至从其中删除了元素.可悲的是,执行此操作的时间跨度似乎是 0:0:0 .结果令人惊讶,我计时执行的方式一定有问题.有人可以帮助我确定代码的正确时间吗?

Even though it is good to check performance of code in terms of algorithmic analysis and Big-Oh! notation i wanted to see how much it takes for the code to execute in my PC. I had initialized a List to 9999count and removed even elements out from the them. Sadly the timespan to execute this seems to be 0:0:0. Surprised by the result there must be something wrong in the way i time the execution. Could someone help me time the code correct?

        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 的内容都没有足够的精度:

The most appropriate thing to use there would be Stopwatch - anything involving TimeSpan has nowhere near enough precision for this:

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

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

However, a modern CPU is very fast, and it would not surprise me if it can remove them in that time. Normally, for timing, you need to repeat an operation a large number of times to get a reasonable measurement.

此外: RemoveEven(参考源)中的 ref 几乎肯定是不需要的.

Aside: the ref in RemoveEven(ref source) is almost certainly not needed.

这篇关于使用Timer计时C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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