本文共 1556 字,大约阅读时间需要 5 分钟。
在项目开发过程中,需要对某些方法的执行时间进行记录和分析。这通常可以通过两种方式实现:Stopwatch类和DateTime.Now.Ticks。
Stopwatch类位于System.Diagnostics命名空间,具有高精度的时间测量功能。Stopwatch对象可以执行以下操作:Start开始计时,Stop停止计时,Reset重置计时器。此外,StartNew方法可以启动一个新的计时器。
以下是一个简单的示例,用于累加1到10,000,000之间的所有整数:
using System;using System.Diagnostics;namespace StopWatchClass{ class Program { static void Main(string[] args) { Stopwatch timer = new Stopwatch(); long total = 0; timer.Start(); for (int i = 1; i <= 10000000; i++) { total += i; } timer.Stop(); decimal micro = timer.Elapsed.Ticks / 10m; Console.WriteLine("执行时间为 {0:F1} 微秒", micro); } }}
另一种方法是使用DateTime.Now.Ticks获取当前时间的微秒数。具体操作如下:
例如:
using System;namespace DateTimeClass{ class Program { static void Main(string[] args) { // 记录开始时间 long begin = DateTime.Now.Ticks; // 执行时间敏感的代码 for (int i = 1; i <= 10000000; i++) { // 模拟耗时操作 System.Threading.Thread.Sleep(1); } // 记录结束时间 long end = DateTime.Now.Ticks; // 计算总时间(以微秒为单位) long duration = end - begin; decimal seconds = duration / 10000000m; Console.WriteLine("总耗时:{0} 秒", seconds); } }}