|
| 1 | +using System; |
| 2 | +using System.Buffers; |
| 3 | +using System.Collections.Generic; |
| 4 | +using BenchmarkDotNet.Attributes; |
| 5 | +using BenchmarkDotNet.Jobs; |
| 6 | + |
| 7 | +namespace MithrilShards.Network.Benchmark.Benchmarks |
| 8 | +{ |
| 9 | + [SimpleJob(RuntimeMoniker.NetCoreApp31)] |
| 10 | + [RankColumn, MarkdownExporterAttribute.GitHub, MemoryDiagnoser] |
| 11 | + public class BlockLocatorBuilding |
| 12 | + { |
| 13 | + [Params(1_000, 100_000, 10_000_000)] |
| 14 | + public int top_height; |
| 15 | + |
| 16 | + [Benchmark] |
| 17 | + public Span<int> Log() |
| 18 | + { |
| 19 | + int itemsToAdd = this.top_height <= 10 ? (this.top_height + 1) : (10 + (int)Math.Ceiling(Math.Log2(this.top_height))); |
| 20 | + Span<int> indexes = new Span<int>(ArrayPool<int>.Shared.Rent(itemsToAdd), 0, itemsToAdd); |
| 21 | + |
| 22 | + int index = 0; |
| 23 | + int current = this.top_height; |
| 24 | + while (index < 10 && current > 0) |
| 25 | + { |
| 26 | + indexes[index++] = current--; |
| 27 | + } |
| 28 | + |
| 29 | + int step = 1; |
| 30 | + while (current > 0) |
| 31 | + { |
| 32 | + indexes[index++] = current; |
| 33 | + step *= 2; |
| 34 | + current -= step; |
| 35 | + } |
| 36 | + indexes[itemsToAdd - 1] = 0; |
| 37 | + |
| 38 | + return indexes; |
| 39 | + } |
| 40 | + |
| 41 | + [Benchmark] |
| 42 | + public List<int> Loop() |
| 43 | + { |
| 44 | + // Modify the step in the iteration. |
| 45 | + int step = 1; |
| 46 | + List<int> indexes = new List<int>(); |
| 47 | + |
| 48 | + // Start at the top of the chain and work backwards. |
| 49 | + for (int index = this.top_height; index > 0; index -= step) |
| 50 | + { |
| 51 | + // Push top 10 indexes first, then back off exponentially. |
| 52 | + if (indexes.Count >= 10) |
| 53 | + step *= 2; |
| 54 | + |
| 55 | + indexes.Add(index); |
| 56 | + } |
| 57 | + |
| 58 | + // Push the genesis block index. |
| 59 | + indexes.Add(0); |
| 60 | + return indexes; |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments