Skip to content

Instantly share code, notes, and snippets.

@Liminiens
Created July 10, 2018 07:46
Show Gist options
  • Save Liminiens/bba55fb75d879d6fb4d8378bc0575bdf to your computer and use it in GitHub Desktop.
Save Liminiens/bba55fb75d879d6fb4d8378bc0575bdf to your computer and use it in GitHub Desktop.
internal static class Program
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
private static void Main(string[] args)
{
long frequency, start, stop;
double multiplier = 1000 * 1000 * 1000;//nano
if (QueryPerformanceFrequency(out frequency) == false)
{
throw new Win32Exception();
}
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
const int gigahertz = 1000 * 1000 * 1000;
const int knownInstructionsPerLoop = 1;
int iterations = int.MaxValue;
int g = 0;
QueryPerformanceCounter(out start);
for (var i = 0; i < iterations; i++)
{
g++;
g++;
g++;
g++;
}
QueryPerformanceCounter(out stop);
var normalTicksPerSecond = frequency * 1000;
var ticks = (double)(stop - start);
var time = (ticks * multiplier) / frequency;
var loopsPerSec = iterations / (time / multiplier);
var instructionsPerLoop = normalTicksPerSecond / loopsPerSec;
var ratio = (instructionsPerLoop / knownInstructionsPerLoop);
var actualFreq = normalTicksPerSecond / ratio;
Console.WriteLine("Perf counhter freq: {0:n}", normalTicksPerSecond);
Console.WriteLine("Loops per sec: {0:n}", loopsPerSec);
Console.WriteLine("Perf counter freq div loops per sec: {0:n}", instructionsPerLoop);
Console.WriteLine("Presumed freq: {0:n}", actualFreq);
Console.WriteLine("ratio: {0:n}", ratio);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment