static void Test() {
SpeedTester.Start(10, () => {
var d = DateTime.UtcNow;
}, () => {
var d = Environment.TickCount;
});
}
/// <summary>
/// 测量代码执行速度的方法
/// </summary>
public static class SpeedTester {
/// <summary>
/// 测试单个函数的执行速度
/// </summary>
public static void Start(Action action, string flag, int i = 0) {
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
Console.WriteLine($"第{i + 1}次 {flag} 耗时:{sw.ElapsedMilliseconds}毫秒,Ticks={sw.ElapsedTicks}");
}
/// <summary>
/// 测试多个函数的执行速度
/// </summary>
/// <param name="count">测试的次数</param>
/// <param name="actions">测试的函数</param>
public static void Start(int count, params Action[] actions) {
Console.WriteLine("============================================");
for (int i = 0; i < count; i++) {
for (int j = 0; j < actions.Length; j++) {
Start(actions[j], $"第{j + 1}个方法", i);
}
Console.WriteLine("============================================");
}
}
}