using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Serein.Library.Utils { /// /// 代码计时工具类 /// public static class BenchmarkHelpers { /// /// 运行指定异步方法多次并输出耗时的最大、最小和平均值。 /// /// 需要执行的方法 /// 执行次数,默认10000 public static void Benchmark(Action action, int count = 10000) { double max = double.MinValue; double min = double.MaxValue; double total = 0; for (int i = 0; i < count; i++) { var sw = Stopwatch.StartNew(); action(); sw.Stop(); double ms = sw.Elapsed.TotalMilliseconds; if (ms > max) max = ms; if (ms < min) min = ms; total += ms; } double avg = total / count; SereinEnv.WriteLine(InfoType.INFO, $"运行 {count} 次:"); SereinEnv.WriteLine(InfoType.INFO, $"总耗时 :{total} 毫秒:"); SereinEnv.WriteLine(InfoType.INFO, $"最大耗时:{max} 毫秒"); SereinEnv.WriteLine(InfoType.INFO, $"最小耗时:{min} 毫秒"); SereinEnv.WriteLine(InfoType.INFO, $"平均耗时:{avg} 毫秒"); } /// /// 运行指定异步方法多次并输出耗时的最大、最小和平均值。 /// /// 需要执行的异步方法 /// 执行次数,默认10000 public static async Task BenchmarkAsync(Func func, int count = 10000) { double max = double.MinValue; double min = double.MaxValue; double total = 0; for (int i = 0; i < count; i++) { var sw = Stopwatch.StartNew(); await func(); sw.Stop(); double ms = sw.Elapsed.TotalMilliseconds; if (ms > max) max = ms; if (ms < min) min = ms; total += ms; } double avg = total / count; SereinEnv.WriteLine(InfoType.INFO, $"运行 {count} 次:"); SereinEnv.WriteLine(InfoType.INFO, $"总耗时 :{total} 毫秒:"); SereinEnv.WriteLine(InfoType.INFO, $"最大耗时:{max} 毫秒"); SereinEnv.WriteLine(InfoType.INFO, $"最小耗时:{min} 毫秒"); SereinEnv.WriteLine(InfoType.INFO, $"平均耗时:{avg} 毫秒"); } /// /// 运行指定异步方法多次并输出耗时的最大、最小和平均值。 /// /// 需要执行的异步方法 /// 执行次数,默认10000 public static async Task BenchmarkAsync(Func> func, int count = 10000) { double max = double.MinValue; double min = double.MaxValue; double total = 0; TReult result = default; for (int i = 0; i < count; i++) { var sw = Stopwatch.StartNew(); result = await func(); sw.Stop(); double ms = sw.Elapsed.TotalMilliseconds; if (ms > max) max = ms; if (ms < min) min = ms; total += ms; //Console.WriteLine($"第{count}次: 耗时 {ms} ms"); } double avg = total / count; SereinEnv.WriteLine(InfoType.INFO, $"运行 {count} 次:"); SereinEnv.WriteLine(InfoType.INFO, $"总耗时 :{total} 毫秒:"); SereinEnv.WriteLine(InfoType.INFO, $"最大耗时:{max} 毫秒"); SereinEnv.WriteLine(InfoType.INFO, $"最小耗时:{min} 毫秒"); SereinEnv.WriteLine(InfoType.INFO, $"平均耗时:{avg} 毫秒"); return result; } /// /// 运行指定异步方法多次并输出耗时的最大、最小和平均值。 /// /// 需要执行的异步方法 public static async Task BenchmarkAsync(Func> func) { double max = double.MinValue; double min = double.MaxValue; double total = 0; TReult result = default; var sw = Stopwatch.StartNew(); result = await func(); sw.Stop(); double ms = sw.Elapsed.TotalMilliseconds; if (ms > max) max = ms; if (ms < min) min = ms; total += ms; var tips = $"运行耗时 :{total} 毫秒:"; SereinEnv.WriteLine(InfoType.INFO, tips); return result; } } }