首页 > 代码库 > c#实现统计代码运行时间

c#实现统计代码运行时间

方法一:

 //实例化一个计时器
Stopwatch watch = new Stopwatch();
//開始计时
watch.Start();

//此处为要计算的执行代码
for (int i = 1; i < 1000000; i++) { }   // Execute the task to be timed

//结束计时
watch.Stop();

//获取当前实例測量得出的总执行时间(以毫秒为单位)
string time = watch.ElapsedMilliseconds.ToString();
//说明:Stopwatch提供了几个方法用以控制Stopwatch对象。Start方法開始一个计时操作。Stop方法停止计时。

为避免这样的情况。在第二次计时前用Reset方法将对象归零
 
Console.WriteLine("Elapsed: {0}",watch.Elapsed);
Console.WriteLine("In milliseconds: {0}",watch.ElapsedMilliseconds);
Console.WriteLine("In timer ticks: {0}",watch.ElapsedTicks);


方法二:

DateTime startTime = DateTime.Now;
Console.WriteLine ("Started: {0}", startTime);
 
// Execute the task to be timed
for (int i=1; i < 100000; i++){}  

DateTime stopTime = DateTime.Now;
Console.WriteLine ("Stopped: {0}", stopTime);

TimeSpan elapsedTime = stopTime - startTime;
Console.WriteLine ("Elapsed: {0}", elapsedTime);
Console.WriteLine ("in hours       :" + elapsedTime.TotalHours);
Console.WriteLine ("in minutes     :" + elapsedTime.TotalMinutes);
Console.WriteLine ("in seconds     :" + elapsedTime.TotalSeconds);
Console.WriteLine ("in milliseconds:" + elapsedTime.TotalMilliseconds);

c#实现统计代码运行时间