High resolution timer in .NET

后端 未结 4 1957
一整个雨季
一整个雨季 2020-12-09 14:57

I\'d like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs th

4条回答
  •  無奈伤痛
    2020-12-09 15:52

    Here is a sample bit of code to time an operation:

    Dim sw As New Stopwatch()
    sw.Start()
    //Insert Code To Time
    sw.Stop()
    Dim ms As Long = sw.ElapsedMilliseconds
    Console.WriteLine("Total Seconds Elapsed: " & ms / 1000)
    

    EDIT:

    And the neat thing is that it can resume as well.

    Stopwatch sw = new Stopwatch();
    foreach(MyStuff stuff in _listOfMyStuff)
    {
        sw.Start();
        stuff.DoCoolCalculation();
        sw.Stop();
    }
    Console.WriteLine("Total calculation time: {0}", sw.Elapsed);
    

    The System.Diagnostics.Stopwatch class will use a high-resolution counter if one is available on your system.

提交回复
热议问题