Stopwatch类:http://msdn.microsoft.com/zh-cn/library/system.diagnostics.stopwatch(v=vs.100).aspx
常用属性和方法:
Start(): 开始或继续测量某个时间间隔的运行时间。
Stop(): 停止测量某个时间间隔的运行时间。
ElapsedMilliseconds:获取当前实例测量得出的总运行时间(以毫秒为单位)。
例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace BoxAndUnBox { class Program { static void Main(string[] args) { Stopwatch watch = new Stopwatch(); watch.Start(); long result = SumWithoutBox(); watch.Stop(); Console.WriteLine("SumWithoutBox()方法返回计算结果:{0},用时{1}毫秒", result, watch.ElapsedMilliseconds);//获取当前实例测量得出的总运行时间(以毫秒为单位) watch.Restart(); result = SumWithBox(); watch.Stop(); Console.WriteLine("SumWithBox()方法返回计算结果:{0},用时{1}毫秒", result, watch.ElapsedMilliseconds); Console.ReadKey(); } static long SumWithoutBox() { long sum = 0; for (long i = 0; i < 10000000; i++) sum += i; return sum; } static long SumWithBox() { object sum = 0L; //装箱 for (long i = 0; i < 10000000; i++) sum = (long)sum + i;//先拆箱,求和,再装箱 return (long)sum;//拆箱 } } }
------------>>>
.NET/C# 使用Stopwatch测量运行时间
时间: 2024-11-05 07:44:23