1. Use Stopwatch
classes to calculate the running time of a program. Stopwatch
Provides high-precision timing functions that can be used to measure the execution time of code blocks or entire programs. Here's an example:
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
// 创建 Stopwatch 实例
Stopwatch stopwatch = new Stopwatch();
// 开始计时
stopwatch.Start();
// 执行需要计时的代码块
DoSomething();
// 停止计时
stopwatch.Stop();
// 获取运行时间
TimeSpan elapsedTime = stopwatch.Elapsed;
// 输出运行时间
Console.WriteLine("程序运行时间: " + elapsedTime);
// 输出以毫秒为单位的运行时间
Console.WriteLine("程序运行时间(毫秒): " + elapsedTime.TotalMilliseconds);
}
static void DoSomething()
{
// 模拟需要计时的代码块
for (int i = 0; i < 1000000; i++)
{
// 执行一些操作
}
}
}
The above code uses Stopwatch
classes to calculate DoSomething()
the running time of a block of code. The method is called when the program starts Start()
to start timing, and Stop()
the method is called after the code block is executed to stop timing. Elapsed
The object of the running time can be obtained through the properties TimeSpan
, and its various properties (such as total time, milliseconds, etc.) can be used for output or other operations.
Note that Stopwatch
the timing accuracy of a class will be affected by the system and hardware. Generally, it can reach microsecond level accuracy.