From ded94ab8b9f9f2119f04236a6b8fc2c230124d21 Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Sun, 19 Mar 2017 01:55:28 +0100 Subject: [PATCH] IterateArray benchmark --- .../General/IterateArray.cs | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 tests/ImageSharp.Benchmarks/General/IterateArray.cs diff --git a/tests/ImageSharp.Benchmarks/General/IterateArray.cs b/tests/ImageSharp.Benchmarks/General/IterateArray.cs new file mode 100644 index 0000000000..48f2316a27 --- /dev/null +++ b/tests/ImageSharp.Benchmarks/General/IterateArray.cs @@ -0,0 +1,70 @@ +namespace ImageSharp.Benchmarks.General +{ + using System.Numerics; + using System.Runtime.CompilerServices; + + using BenchmarkDotNet.Attributes; + + public class IterateArray + { + // Usual pinned stuff + private PinnedBuffer buffer; + + // An array that's not pinned by intent! + private Vector4[] array; + + [Params(64, 1024)] + public int Length { get; set; } + + [Setup] + public void Setup() + { + this.buffer = new PinnedBuffer(this.Length); + this.array = new Vector4[this.Length]; + } + + [Benchmark(Baseline = true)] + public Vector4 IterateIndexed() + { + Vector4 sum = new Vector4(); + Vector4[] a = this.array; + + for (int i = 0; i < a.Length; i++) + { + sum += a[i]; + } + return sum; + } + + [Benchmark] + public unsafe Vector4 IterateUsingPointers() + { + Vector4 sum = new Vector4(); + + Vector4* ptr = (Vector4*) this.buffer.Pointer; + Vector4* end = ptr + this.Length; + + for (; ptr < end; ptr++) + { + sum += *ptr; + } + + return sum; + } + + [Benchmark] + public Vector4 IterateUsingReferences() + { + Vector4 sum = new Vector4(); + + ref Vector4 start = ref this.array[0]; + + for (int i = 0; i < this.Length; i++) + { + sum += Unsafe.Add(ref start, i); + } + + return sum; + } + } +} \ No newline at end of file