Timing C# code using Timer

我们两清 提交于 2021-01-28 08:01:22

问题


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();

回答1:


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);

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.

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




回答2:


In .Net 2.0 you can use the Stopwatch class

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

Stopwatch watch = new Stopwatch();

watch.Start();
RemoveEven(ref source);
//watch.ElapsedMilliseconds contains the execution time in ms
watch.Stop()



回答3:


Adding to previous answers:

var sw = Stopwatch.StartNew();

// instructions to time

sw.Stop();

sw.ElapsedMilliseconds returns a long and has a resolution of:

1 millisecond = 1000000 nanoseconds

sw.Elapsed.TotalMilliseconds returns a double and has a resolution equal to the inverse of Stopwatch.Frequency. On my PC for example Stopwatch.Frequency has a value of 2939541 ticks per second, that gives sw.Elapsed.TotalMilliseconds a resolution of:

1/2939541 seconds = 3,401891655874165e-7 seconds = 340 nanoseconds



来源:https://stackoverflow.com/questions/10811039/timing-c-sharp-code-using-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!