计算代码运行时间
在优化代码过程中,有时需要统计一些代码的运行时间。
在 C# 中有几种方式可以用来统计代码的运行时间,如:DateTime
或 Stopwatch
,一般推荐使用Stopwatch,其精度较高,但无论哪种方式都会有一定的误差存在。
1、 Stopwatch
using System;
using System.Threading;
using System.Diagnostics; // Used for: Stopwatch
namespace BaseTmpDemo
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw01 = new Stopwatch();
sw01.Start();
DoSomething();
sw01.Stop();
Console.WriteLine($"Elapsed Time = {sw01.ElapsedMilliseconds} ms");
Console.ReadKey();
}
// 需要被统计运行时间的代码
static void DoSomething()
{
Thread.Sleep(1000);
}
}
}
2、DateTime
using System;
using System.Threading;
namespace BaseTmpDemo
{
class Program
{
static void Main(string[] args)
{
DateTime startTime = DateTime.Now;
DoSomething();
DateTime endTime = DateTime.Now;
double elapsedTime = (endTime - startTime).TotalMilliseconds;
Console.WriteLine($"Elapsed Time = {elapsedTime} ms");
Console.ReadKey();
}
static void DoSomething()
{
Thread.Sleep(1000);
}
}
}
【参考资料】