查找方法的执行时间

use*_*754 9 .net c#

我正在为我的大学制作一个图像隐写术项目.我已完成项目并保留了几种不同的算法来隐藏图像中的数据.

我想问的是,在C#中有什么方法可以通过它找到程序中两点之间的执行/运行时间.例如

//Some Code
//Code to start recording the time.
hideDataUsingAlgorithm();
//Code to stop recording and get the time of execution of the above function. 
Run Code Online (Sandbox Code Playgroud)

我想这样做是为了显示简单(耗时较少)和更高效但耗时的算法(使用相同的数据和相同的图像)之间的区别.我有大约10种不同的Color和GrayScale图像算法.

没有多线程因此不会成为问题.Theres只是一个主线程.

Joh*_*son 14

这是一个有用的秒表扩展方法:

public static class StopwatchExt
{
    public static string GetTimeString(this Stopwatch stopwatch, int numberofDigits = 1)
    {
        double time = stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
        if (time > 1)
            return Math.Round(time, numberofDigits) + " s";
        if (time > 1e-3)
            return Math.Round(1e3 * time, numberofDigits) + " ms";
        if (time > 1e-6)
            return Math.Round(1e6 * time, numberofDigits) + " µs";
        if (time > 1e-9)
            return Math.Round(1e9 * time, numberofDigits) + " ns";
        return stopwatch.ElapsedTicks + " ticks";
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

Stopwatch stopwatch = Stopwatch.StartNew();
//Call your method here
stopwatch.Stop();
Console.WriteLine(stopwatch.GetTimeString());
Run Code Online (Sandbox Code Playgroud)


Oba*_*ama 12

System.Environment.TickCountSystem.Diagnostics.Stopwatch类是两个适用于更精细的分辨率和直接使用的类.

也可以看看:

  1. 是DateTime.Now是测量函数性能的最佳方法吗?
  2. .NET中的高分辨率计时器
  3. Environment.TickCount与DateTime.Now
  4. 在Windows中对程序进行基准测试的最佳方法是什么?

  • 绝对使用`Stopwatch`类进行性能测试.`TickCount`对于基准测试并不是特别有用. (3认同)