-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBenchmarkTask.cs
More file actions
58 lines (54 loc) · 1.61 KB
/
Copy pathBenchmarkTask.cs
File metadata and controls
58 lines (54 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Diagnostics;
using System.Text;
using NUnit.Framework;
namespace StructBenchmarking
{
public class Benchmark : IBenchmark
{
public double MeasureDurationInMs(ITask task, int repetitionCount)
{
var timer = new Stopwatch();
GC.Collect();
GC.WaitForPendingFinalizers();
task.Run();
timer.Start();
for (var i = 0; i < repetitionCount; i++)
task.Run();
timer.Stop();
return timer.Elapsed.TotalMilliseconds / repetitionCount;
}
}
[TestFixture]
public class RealBenchmarkUsageSample
{
private class BuilderTest : ITask
{
public void Run()
{
var builder = new StringBuilder();
for (var i = 0; i < 10000; i++)
builder.Append("a");
var temp = builder.ToString();
builder.Clear();
}
}
private class StringTest : ITask
{
public void Run()
{
var temp = new string('a', 10000);
}
}
[Test]
public void StringConstructorFasterThanStringBuilder()
{
var builderTest = new BuilderTest();
var stringTest = new StringTest();
var benchmark = new Benchmark();
var builderTestResult = benchmark.MeasureDurationInMs(builderTest, 10);
var stringTestResult = benchmark.MeasureDurationInMs(stringTest, 10);
Assert.Less(stringTestResult, builderTestResult);
}
}
}