1.Stopwatch类
- Stopwatch timer = new Stopwatch();
- timer.Start();
- //要测试的代码
- timer.Stop();
运行时间 = timer.Elapsed.TotalMilliseconds;
单位是毫秒,精确到万分位。
如果不要求到如此高的精确度的话,也可以使用timer.ElapsedMilliseconds;精确到毫秒的整数。
当然,还可以用计时周期timer.ElapsedTicks;来表示。
2.
- [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
- static extern bool QueryPerformanceCounter(ref long count);
- [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
- static extern bool QueryPerformanceFrequency(ref long count);
- [STAThread]
- static void Main(string[] args)
- {
- long count = 0;
- long count1 = 0;
- long freq = 0;
- double result = 0;
- QueryPerformanceFrequency(ref freq);
- QueryPerformanceCounter(ref count);
- //需要测试的模块
- int heisetoufa;
- for (heisetoufa = 1; heisetoufa < 10000; heisetoufa++)
- {
- Console.WriteLine("第" + heisetoufa + "行");
- if (heisetoufa == 5000)
- {
- Thread.Sleep(10000);
- }
- }
- //需要测试的模块
- QueryPerformanceCounter(ref count1);
- count = count1 - count;
- result = (double)(count) / (double)freq;
- Console.WriteLine("耗时: {0} 秒", result);
- Console.ReadLine();
- }
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秒的