在软件开发领域,性能基准测试是确保软件系统高效、稳定运行的重要环节。它可以帮助你评估应用程序的性能,了解其在不同条件下的响应时间、吞吐量、资源利用率等。通过基准测试,你可以确定系统在处理特定工作负载时的性能表现。
[MemoryDiagnoser]//记录内存分配情况 public class HashFunctionsBenchmark { private readonly string _inputData; public HashFunctionsBenchmark() { // 使用一个较长的字符串作为输入,以更好地反映哈希函数的性能 _inputData = new string('y', 1000000); } [Benchmark] public byte[] MD5Hash() { using (MD5 md5 = MD5.Create()) { // 堆代码 duidaima.com return md5.ComputeHash(Encoding.UTF8.GetBytes(_inputData)); } } [Benchmark] public byte[] SHA256Hash() { using (SHA256 sha256 = SHA256.Create()) { return sha256.ComputeHash(Encoding.UTF8.GetBytes(_inputData)); } } [Benchmark] public byte[] SHA1Hash() { using (SHA1 sha1 = SHA1.Create()) { return sha1.ComputeHash(Encoding.UTF8.GetBytes(_inputData)); } } }运行基准测试
internal class Program { static void Main(string[] args) { var summary = BenchmarkRunner.Run<HashFunctionsBenchmark>(); } }注意一定要设置为:Release模式运行,假如为Debug模式会提示下面异常:
// Validating benchmarks: // * Assembly BenchmarkDotNetExercise which defines benchmarks is non-optimized Benchmark was built without optimization enabled (most probably a DEBUG configuration). Please, build it in RELEASE. If you want to debug the benchmarks, please see https://benchmarkdotnet.org/articles/guides/troubleshooting.html#debugging-benchmarks.
Method | Mean | Error | StdDev | Gen0 | Gen1 | Gen2 | Allocated |
---|---|---|---|---|---|---|---|
MD5Hash | 1.952 ms | 0.0169 ms | 0.0158 ms | 197.2656 | 197.2656 | 197.2656 | 976.9 KB |
SHA256Hash | 3.907 ms | 0.0157 ms | 0.0147 ms | 195.3125 | 195.3125 | 195.3125 | 976.93 KB |
SHA1Hash | 1.780 ms | 0.0231 ms | 0.0193 ms | 197.2656 | 197.2656 | 197.2656 | 976.92 KB |
[MarkdownExporter, AsciiDocExporter, HtmlExporter, CsvExporter, RPlotExporter] public class HashFunctionsBenchmark { }