C#测试代码执行效率的3种方式

1.Stopwatch类

  1. Stopwatch timer = new Stopwatch();  
  2. timer.Start();  
  3. //要测试的代码  
  4. timer.Stop(); 

运行时间 = timer.Elapsed.TotalMilliseconds;
单位是毫秒,精确到万分位。
如果不要求到如此高的精确度的话,也可以使用timer.ElapsedMilliseconds;精确到毫秒的整数。
当然,还可以用计时周期timer.ElapsedTicks;来表示。

2.

  1.  [System.Runtime.InteropServices.DllImport("Kernel32.dll")]   
  2.     static extern bool QueryPerformanceCounter(ref long count);   
  3.     [System.Runtime.InteropServices.DllImport("Kernel32.dll")]   
  4.     static extern bool QueryPerformanceFrequency(ref long count);   
  5.     [STAThread]   
  6.     static void Main(string[] args)   
  7.     {   
  8.         long count = 0;   
  9.         long count1 = 0;   
  10.         long freq = 0;   
  11.         double result = 0;   
  12.         QueryPerformanceFrequency(ref freq);   
  13.         QueryPerformanceCounter(ref count);   
  14.         //需要测试的模块   
  15.   
  16.         int heisetoufa;   
  17.         for (heisetoufa = 1; heisetoufa < 10000; heisetoufa++)   
  18.         {   
  19.             Console.WriteLine("第" + heisetoufa + "行");   
  20.             if (heisetoufa == 5000)   
  21.             {   
  22.                 Thread.Sleep(10000);   
  23.             }   
  24.         }   
  25.   
  26.         //需要测试的模块   
  27.   
  28.         QueryPerformanceCounter(ref count1);   
  29.         count = count1 - count;   
  30.         result = (double)(count) / (double)freq;   
  31.         Console.WriteLine("耗时: {0} 秒", result);   
  32.         Console.ReadLine();   
  33.     }   
3.timeSpan

TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks); //获取当前时间的刻度数
            
//执行某操作
            TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);

            TimeSpan ts 
= ts2.Subtract(ts1).Duration(); //时间差的绝对值

            
string spanTotalSeconds = ts.TotalSeconds.ToString(); //执行时间的总秒数
            string spanTime = ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + ""  + ts.Seconds.ToString() + ""//以X小时X分X秒的

你可能感兴趣的:(C#高级语法)