Skip to content

Instantly share code, notes, and snippets.

@jackmott
Last active August 24, 2016 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackmott/3df8b8d4b5e72d1796d70881be00b8f5 to your computer and use it in GitHub Desktop.
Save jackmott/3df8b8d4b5e72d1796d70881be00b8f5 to your computer and use it in GitHub Desktop.
sample benchmark
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Diagnostics.Windows;
namespace bigo
{
[Config(typeof(Config))]
public class Bench
{
private class Config : ManualConfig
{
public Config()
{
Add(Job.RyuJitX64);
Add(new MemoryDiagnoser());
}
}
public int[] rawArray;
public List<int> arrayList;
public LinkedList<int> linkedList;
[Params(100000)]
public int length { get; set; }
[Params(5,10,15)]
public int inserts { get; set; }
[Setup]
public void setupData()
{
// rawArray = new int[this.length];
arrayList = new List<int>();
linkedList = new LinkedList<int>();
for (int i = 0; i < this.length; i++)
{
// rawArray[i] = 1;
arrayList.Add(1);
linkedList.AddFirst(1);
}
}
[Benchmark(Baseline = true)]
public int ArrayTest()
{
//In C#, List<T> is an array backed list.
List<int> local = arrayList;
int localInserts = inserts;
int sum = 0;
for (int j = 0; j < 100; j++)
{
sum = 0;
local.Insert(0, 1); //Insert the number 1 at the front
if (j % localInserts == 0)
{
// For loops iterate over List<T> much faster than foreach
for (int i = 0; i < local.Count; i++)
{
sum += local[i]; //do some work here so the JIT doesn't elide the loop entirely
}
}
}
return sum;
}
[Benchmark]
public int ListTest()
{
LinkedList<int> local = linkedList;
int localInserts = inserts;
int sum = 0;
for (int j = 0; j < 100; j++)
{
sum = 0;
local.AddFirst(1); //Insert the number 1 at the front
if (j % localInserts == 0)
{
var node = local.First;
// For loops iterate over List<T> much faster than foreach
for (int i = 0; i < local.Count; i++)
{
sum += node.Value;
node = node.Next;
}
}
}
return sum;
}
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<Bench>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment