计算程序运行的时间

在工作学习中,经常会遇到计算程序运行时间问题,下面介绍2中常用的方法计算程序运行时间。

一、StopWatch

 1 static void Main(string[] args)
 2 {
 3     //定义一个StopWatch对象
 4     System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
 5     // 开始计时
 6     timer.Start(); 
 7     for (int i = 0; i < 10 * 1000 * 1000; i++)
 8     {
 9         Console.WriteLine(i + "test");
10     }
11     // 停止计时
12     timer.Stop();
13 
14     //输出运行时间
15     Console.WriteLine("程序的运行时间:{0} 秒", timer.Elapsed.Seconds);
16     Console.WriteLine("程序的运行时间:{0} 毫秒", timer.Elapsed.Milliseconds);
17 }

 

二、DateTime.Now

static void Main(string[] args)
{
    //开始时间
    DateTime timeStart = DateTime.Now;
    for (int i = 0; i < 10 * 1000 * 1000; i++)
    {
        Console.WriteLine(i);
    }
    //结束时间
    DateTime timeEnd = DateTime.Now;
    //求时间差的函数
    TimeSpan timeSpan = timeEnd.Subtract(timeStart);
    Console.WriteLine(timeSpan.ToString());
}

  

 

原文地址:https://www.cnblogs.com/fanyong/p/2728681.html