How long does my code take to run?

后端 未结 6 1605
轮回少年
轮回少年 2021-02-05 22:43

How can I find out how much time my C# code takes to run?

6条回答
  •  無奈伤痛
    2021-02-05 23:02

    The Stopwatch class offers high-precision timing in .NET. It is capable of measuring time with sensitivity of around 100s of nanoseconds (fractions of milliseconds). To get the exact resolution, read the value of Stopwatch.Frequency.

    var timer = System.Diagnostics.Stopwatch.StartNew();
    // Run code here.
    var elapsed = timer.ElapsedMilliseconds.
    

    Also, be sure to run your code repeatedly (as many times as is feasible) to get a better average time, as well as to reduce the effects of fluctuations in CPU load.

提交回复
热议问题