Skip to content

Instantly share code, notes, and snippets.

@ilya-g
Created January 22, 2015 22:35
Show Gist options
  • Save ilya-g/860181bd923026450793 to your computer and use it in GitHub Desktop.
Save ilya-g/860181bd923026450793 to your computer and use it in GitHub Desktop.
Interface generic methods call time microbenchmark
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace GenericBencmark
{
class Program
{
public interface ITest
{
void Generic<T>(T arg);
void NonGeneric(long arg);
}
public class Test : ITest
{
public bool isEnabled = false;
public bool IsEnabled { get { return isEnabled; } }
public void Generic<T>(T arg)
{
if (IsEnabled)
DoLog(arg);
}
public void NonGeneric(long arg)
{
if (IsEnabled)
DoLog(arg);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void DoLog<T>(T arg) { }
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Spin<T>(T arg) { }
public static void Main()
{
int iterations = 1000 * 1000 * 1000;
long value = new Random().Next();
Test testInst = new Test() { isEnabled = false };
ITest testItf = testInst;
testItf.Generic(value);
testItf.NonGeneric(value);
var swLoop = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
Spin(value);
}
swLoop.Stop();
var swNonGeneric = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
Spin(value);
testItf.NonGeneric(value);
}
swNonGeneric.Stop();
var swGeneric = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
Spin(value);
testItf.Generic(value);
}
swGeneric.Stop();
var swInstNonGeneric = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
Spin(value);
testInst.NonGeneric(value);
}
swInstNonGeneric.Stop();
var swInstGeneric = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
Spin(value);
testInst.Generic(value);
}
swInstGeneric.Stop();
Console.WriteLine(swLoop.Elapsed);
Console.WriteLine("Instance Generic: {0:0.00} ns/call", ConvertToNsPerIteration(swInstGeneric.Elapsed - swLoop.Elapsed, iterations));
Console.WriteLine("Instance NonGeneric: {0:0.00} ns/call", ConvertToNsPerIteration(swInstNonGeneric.Elapsed - swLoop.Elapsed, iterations));
Console.WriteLine("Interface Generic: {0:0.00} ns/call", ConvertToNsPerIteration(swGeneric.Elapsed - swLoop.Elapsed, iterations));
Console.WriteLine("Interface NonGeneric: {0:0.00} ns/call", ConvertToNsPerIteration(swNonGeneric.Elapsed - swLoop.Elapsed, iterations));
}
private static double ConvertToNsPerIteration(TimeSpan elapsed, int iterations)
{
return elapsed.TotalSeconds*1000000000/iterations;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment