Advertisement
mikhailemv

Практика «Benchmark»

Dec 17th, 2022
1,284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using NUnit.Framework;
  6.  
  7. namespace StructBenchmarking
  8. {
  9.     public class Benchmark : IBenchmark
  10.     {
  11.         public double MeasureDurationInMs(ITask task, int repetitionCount)
  12.         {
  13.             GC.Collect();                  
  14.             GC.WaitForPendingFinalizers();  
  15.  
  16.             task.Run();
  17.  
  18.             var stopwatch = Stopwatch.StartNew();
  19.             for (var i = 0; i < repetitionCount; i++)
  20.             {
  21.                 task.Run();
  22.             }
  23.             stopwatch.Stop();
  24.             return stopwatch.ElapsedMilliseconds / (double)repetitionCount;
  25.         }
  26.     }
  27.  
  28.     [TestFixture]
  29.     public class RealBenchmarkUsageSample
  30.     {
  31.         [Test]
  32.         public void StringConstructorFasterThanStringBuilder()
  33.         {
  34.             var repetitionCount = 10_000;
  35.             var stirngLength = 10_000;
  36.  
  37.             var sbTask = new StringBuilderTask(stirngLength);
  38.             var scTask = new StringConstructorTask(stirngLength);
  39.  
  40.             var benchmark = new Benchmark();
  41.  
  42.             var actualSbMeasure = benchmark.MeasureDurationInMs(sbTask, repetitionCount);
  43.             var actualScMeasure = benchmark.MeasureDurationInMs(scTask, repetitionCount);
  44.  
  45.             Assert.Less(actualScMeasure, actualSbMeasure);
  46.         }
  47.     }
  48.  
  49.     public class StringBuilderTask : ITask
  50.     {
  51.         private readonly int stringLength;
  52.         private string result;
  53.  
  54.         public StringBuilderTask(int stringLength)
  55.         {
  56.             this.stringLength = stringLength;
  57.         }
  58.  
  59.         public void Run()
  60.         {
  61.             var sb = new StringBuilder();
  62.  
  63.             for (var i = 0; i < stringLength; i++)
  64.             {
  65.                 sb.Append('a');
  66.             }
  67.  
  68.             result = sb.ToString();
  69.         }
  70.     }
  71.  
  72.     public class StringConstructorTask : ITask
  73.     {
  74.         private readonly int stringLength;
  75.         private string result;
  76.  
  77.         public StringConstructorTask(int stringLength)
  78.         {
  79.             this.stringLength = stringLength;
  80.         }
  81.  
  82.         public void Run()
  83.         {
  84.             result = new string('a', stringLength);
  85.         }
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement