如何知道c#中的循环持续时间

Moh*_*ani 1 c# time

我在c#中搜索方法来计算循环的持续时间或任何类似的东西,认为我的程序包含或在" for(...,...,...){}"我需要花费多少时间通过什么是方法输出的类型

Mit*_*eat 5

使用秒表类

提供一组方法和属性,可用于准确测量经过的时间.

    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    // stuff you want to time here...

    stopWatch.Stop();

    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;

    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
Run Code Online (Sandbox Code Playgroud)

秒表通过计算基础计时器机制中的计时器滴答来测量经过的时间.如果安装的硬件和操作系统支持高分辨率性能计数器,则Stopwatch类使用该计数器来测量经过的时间.否则,Stopwatch类使用系统计时器来测量经过的时间.使用FrequencyIsHighResolution字段确定秒表计时实施的精度和分辨率.