使用Timer定时C#代码

Dee*_*ons 1 c# algorithm time code-analysis

即使在算法分析和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();
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

在那里使用最合适的事情是Stopwatch- 任何涉及的东西TimeSpan没有足够的精确度:

var watch = Stopwatch.StartNew();
// something to time
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)

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

除此之外:几乎肯定不需要refin RemoveEven(ref source).