需要知道程序中某个操作执行了多久,可用类似如下的代码计算得知:
TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks); //获取当前时间的刻度数
//执行某操作
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
TimeSpan ts = ts2.Subtract(ts1).Duration(); //时间差的绝对值
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
string spanTotalSeconds = ts.TotalSeconds.ToString(); //执行时间的总秒数
string spanTime = ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒"; //以X小时X分X秒的格式现实执行时间
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)