C#之计算程序运行耗时的方法
方式1 利用System.DateTime.Now
示例代码:
static void Main(string[] args)
{
DateTime dt1 = DateTime.Now;
int sum = 0;
for (int i = 0; i < 1000; i++)
{
sum += 1;
}
DateTime dt2 = DateTime.Now;
TimeSpan ts = dt2.Subtract(dt1);
Console.WriteLine("程序耗时:{0}ms.", ts.TotalMilliseconds);
Console.ReadLine();
}
运行结果:
![]()
方式2 利用Stopwatch
示例代码:
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();

本文介绍了C#中计算程序运行耗时的三种方法:利用System.DateTime.Now、Stopwatch类以及API函数,提供了相应的示例代码和运行结果。
最低0.47元/天 解锁文章
477

被折叠的 条评论
为什么被折叠?



