Skip to content

Instantly share code, notes, and snippets.

@hypeartist
Created January 11, 2024 10:36
Show Gist options
  • Save hypeartist/19bfebf88e849e7dfd523fcc093976df to your computer and use it in GitHub Desktop.
Save hypeartist/19bfebf88e849e7dfd523fcc093976df to your computer and use it in GitHub Desktop.
IsInRange bench
public class Bench
{
private const int Rep = 10_000_000;
private int[] _a = new int[Rep];
[GlobalSetup]
public void Setup()
{
Random.Shared.GetItems([..Enumerable.Range(0, Rep)], _a);
}
[Benchmark(Baseline = true)]
public int IsInRangeV1()
{
var sum = 0;
for (var i = 0; i < Rep; i++)
{
var c = _a[i];
sum += c >= i - 100 && c <= i + 100 ? 1 : 0;
}
return sum;
}
[Benchmark]
public int IsInRangeV2()
{
const long mask = (1L << 63) | (1L << 31);
var sum = 0;
for (var i = 0; i < Rep; i++)
{
var c = (long)_a[i];
var r = (((long)i + 100) << 32) | ((long)i - 100);
var isFit = BitOperations.PopCount((ulong)((((c << 32) | c) - r) & mask)) & 1;
sum += isFit;
}
return sum;
}
[Benchmark]
public int IsInRangeV3()
{
var sum = 0;
for (var i = 0; i < Rep; i++)
{
var c = _a[i];
sum += ((c - (i - 100)) | (i + 100 - c)) > 0 ? 1 : 0;
}
return sum;
}
}
public static void RunBenchmark()
{
var enough = Job.Default
.WithWarmupCount(1)
.WithIterationTime(TimeInterval.FromSeconds(0.25))
.WithMaxIterationCount(20);
IConfig config = DefaultConfig.Instance
.HideColumns(Column.EnvironmentVariables, Column.RatioSD, Column.Error)
.AddDiagnoser(new MemoryDiagnoser(new MemoryDiagnoserConfig(false)))
.AddDiagnoser(new DisassemblyDiagnoser(new DisassemblyDiagnoserConfig(exportGithubMarkdown: true, printInstructionAddresses: false)));
config.AddJob(enough);
BenchmarkRunner.Run<Bench>(config);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment