Last active
March 16, 2020 13:15
-
-
Save benaadams/bf85405a5eae4c750cf6470a5506fd8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.CompilerServices; | |
using System.Runtime.InteropServices; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using nint = System.Int64; | |
public class SequenceEqualThreshold | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkSwitcher.FromAssembly(typeof(SequenceEqualThreshold).Assembly).Run(args); | |
} | |
private GCHandle _inputHandle; | |
private Memory<byte> _input; | |
private GCHandle _expectedHandle; | |
private Memory<byte> _expected; | |
[Params(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, 62, 63, 64, 80, 96, 128, 192, 256, 512, 1024, 2048, 4096)] | |
public int Length; | |
[GlobalSetup] | |
public void Setup() | |
{ | |
var overlength = Length + 4096; | |
var input = new byte[overlength]; | |
var expected = new byte[overlength]; | |
// Need to keep alignment the same between methods and runs | |
_inputHandle = GCHandle.Alloc(input, GCHandleType.Pinned); | |
_expectedHandle = GCHandle.Alloc(expected, GCHandleType.Pinned); | |
var inputOffset = 4096 - (int)((nint)_inputHandle.AddrOfPinnedObject() & 4095); | |
var expectedOffset = 4096 - (int)((nint)_expectedHandle.AddrOfPinnedObject() & 4095); | |
_input = new Memory<byte>(input, inputOffset, Length); | |
_expected = new Memory<byte>(expected, expectedOffset, Length); | |
var inputSpan = _input.Span; | |
var outputSpan = _expected.Span; | |
for (int i = 0; i < Length; i++) | |
{ | |
var value = (byte)i; | |
inputSpan[i] = value; | |
outputSpan[i] = value; | |
} | |
} | |
[Benchmark] | |
public bool UseLinearSearch() | |
{ | |
if (!LinearSearch(_input.Span, _expected.Span)) | |
{ | |
throw new Exception(); | |
} | |
return true; | |
} | |
[Benchmark] | |
public bool UseSequenceEqual() | |
{ | |
if (!_input.Span.SequenceEqual(_expected.Span)) | |
{ | |
throw new Exception(); | |
} | |
return true; | |
} | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
private static bool LinearSearch(Span<byte> input, Span<byte> expected) | |
{ | |
if (input.Length != expected.Length) | |
{ | |
return false; | |
} | |
for (int i = 0; i < input.Length; i++) | |
{ | |
if (input[i] != expected[i]) | |
{ | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment