-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnrollBenchmarks.cs
More file actions
63 lines (51 loc) · 1.35 KB
/
UnrollBenchmarks.cs
File metadata and controls
63 lines (51 loc) · 1.35 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
59
60
61
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
public class UnrollBenchmarks
{
int[]? array;
[Params(10, 1_000_000)]
public int Count { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
var enumerable = Utils.GetEnumerable(Count, 100);
array = enumerable.ToArray();
}
[Benchmark(Baseline = true)]
public int Baseline()
{
var sum = 0;
foreach(var item in array!)
sum += item;
return sum;
}
[Benchmark]
public int Unrolled()
{
var source = array.AsSpan();
ref var sourceRef = ref MemoryMarshal.GetReference(source);
var sum = 0;
#if NET7_0_OR_GREATER
var index = nint.Zero;
#else
var index = (nint)0;
#endif
var end = source.Length - (source.Length % 4);
while (index < end)
{
sum += Unsafe.Add(ref sourceRef, index);
sum += Unsafe.Add(ref sourceRef, index + 1);
sum += Unsafe.Add(ref sourceRef, index + 2);
sum += Unsafe.Add(ref sourceRef, index + 3);
index += 4;
}
// handle remaining elements
while (index < source.Length)
{
sum += Unsafe.Add(ref sourceRef, index);
index++;
}
return sum;
}
}