What is the best way to measure how long code takes to execute?

后端 未结 10 1255
梦谈多话
梦谈多话 2020-12-08 04:04

I\'m trying to determine which approach to removing a string is the fastest.

I simply get the start and end time a

10条回答
  •  青春惊慌失措
    2020-12-08 04:27

    There's a lot of activity going on under the hood of the OS, which is very likely to mess up your time measurements. In order to improve the accuracy of the measured times you should execute the tests multiple times and remove the lowest and the greatest times from the final results. This approach will exclude most of the external factors that may influence your code's execution time and will serve you well in most cases. The Stopwatch class is used to measure time as it is much more accurate than using DateTime.

    You can easily make a test class to automate this. I have published one such class in my blog. It can compare the performance of two C# code fragments/algorithms. All you have to do is to override the Method1 and Method2 methods putting there the code fragments you want to test and use the test class like this:

    Test test = new CustomTest();
    Console.WriteLine("\n==============================");
    Console.WriteLine(test.Execute());
    Console.WriteLine("==============================\n");
    

提交回复
热议问题