Measure the code execution time. The difference between stopwatch and userprocessortime

Source: Internet
Author: User

When we need to calculate the execution time of a piece of code, we may first think of the stopwatch class. Here, we will not use stopwatch for the moment to customize a class for calculating the code execution time. We need to consider the following:

1. Make sure that the time for executing the code in the current process and current thread is counted.
2. Garbage collection is not allowed during statistics execution. That is, before calculating the code execution time, let the GC complete garbage collection.

 

Example: Statistical display of the time consumed by an array element

    class Program
    {
        static void Main(string[] args)
        {
            int[] arrs = new int[10000];
            BuildArray(arrs);
            CalculateTiming calculateTiming = new CalculateTiming();
            calculateTiming.Start();
            DisplaySomeDigits(arrs);
            calculateTiming.Stop();
            Console.WriteLine("所耗费时间为:" + calculateTiming.Result().TotalMilliseconds + "毫秒");
        }
        //显示数组元素
        static void DisplaySomeDigits(int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
        }
        //创建数组
        static void BuildArray(int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = i;
            }
        }
    }
    /// <summary>
    /// 计算CPU消耗时间
    /// </summary>
    public class CalculateTiming
    {
        private TimeSpan startTime;
        private TimeSpan duration;
        public CalculateTiming()
        {
            startTime = new TimeSpan(0);
            duration = new TimeSpan(0);
        }
        public void Start()
        {
            //手动执行垃圾回收
            GC.Collect();
            //挂起当前线程,直到使用GC对所有托管堆上的对象实施Finalize方法
            GC.WaitForPendingFinalizers();
            //获取当前进程、当前线程执行的起始时间
            startTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
        }
        public void Stop()
        {
            //获取当前进程、当前线程执行所消耗的时间
            duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startTime);
        }
        public TimeSpan Result()
        {
            return duration;
        }
    }

Above, the code execution time is counted through the userprocessortime attribute of the current process and current thread.


If you use stopwatch to calculate the code execution time.

        static void Main(string[] args)
        {
            int[] arrs = new int[10000];
            BuildArray(arrs);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            DisplaySomeDigits(arrs);
            sw.Stop();
            Console.WriteLine("所耗费时间为:" + sw.ElapsedMilliseconds + "毫秒");
        }

 

Why does it take longer to use stopwatch to count the code execution time?
-- Use the userprocessortime attribute to calculate the CPU execution time consumed by the current process and current thread. The code execution time measured by stopwatch includes not only the CPU execution time, but also the I/0 time used to display strings on the computer screen.

Measure the code execution time. The difference between stopwatch and userprocessortime

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.