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

本文介绍了几种在C#中进行性能测试的方法,包括使用Stopwatch类进行简单的计时,利用Kernel32.dll进行高精度计时,以及通过TimeSpan计算执行时间。这些方法可以帮助开发者准确地评估代码的执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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秒的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值