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

后端 未结 10 1256
梦谈多话
梦谈多话 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:29

    Three simple notes:

    1. Use System.Diagnostics.Stopwatch.

    2. Don't profile your code on the same input one million times. Try to find your expected distribution of inputs and profile on that. That is profile on real-world input, not laboratory input.

    3. Run the Clean method once before entering the profiling loop to eliminate JITting time. Sometimes this is important.

    Of these, notes 1. and 2. are by far the most important.

    Your profiling results are meaningless if you are not using a high-resolution timer. Note that we don't time Usain Bolt using a water clock.

    Your profiling results are meaningless if you are not testing on real-world input. Note that crash tests crash cars head on into other cars at 35 MPH, not into walls made of marshmellows at 5 MPH.

    Thus:

    // expectedInput is string[1000000]
    // populate expectedInput with real-world input
    Clean(expectedInput[0]);
    Stopwatch sw = new Stopwatch();
    sw.Restart();          //So you dont have to call sw.Reset()
    for (int i = 0; i < 1000000; i++) {
        string t = Clean(expectedInput[i]);
    }
    sw.Stop();
    Console.WriteLine(sw.Elapsed);
    

    One complex note:

    If you really need to do profiling, get a profiler like ANTS.

提交回复
热议问题