Last active
December 30, 2015 05:29
-
-
Save junxy/7783219 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Runtime.InteropServices; | |
using System.Threading; | |
public static class CodeTimer | |
{ | |
public static void Initialize() | |
{ | |
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; | |
Thread.CurrentThread.Priority = ThreadPriority.Highest; | |
Time("", 1, () => { }); | |
} | |
public static void Time(string name, int iteration, Action action) | |
{ | |
if (String.IsNullOrEmpty(name)) return; | |
// 1. | |
ConsoleColor currentForeColor = Console.ForegroundColor; | |
Console.ForegroundColor = ConsoleColor.Yellow; | |
Console.WriteLine(name); | |
// 2. | |
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); | |
int[] gcCounts = new int[GC.MaxGeneration + 1]; | |
for (int i = 0; i <= GC.MaxGeneration; i++) | |
{ | |
gcCounts[i] = GC.CollectionCount(i); | |
} | |
// 3. | |
Stopwatch watch = new Stopwatch(); | |
watch.Start(); | |
ulong cycleCount = GetCycleCount(); | |
for (int i = 0; i < iteration; i++) action(); | |
ulong cpuCycles = GetCycleCount() - cycleCount; | |
watch.Stop(); | |
// 4. | |
Console.ForegroundColor = currentForeColor; | |
Console.WriteLine("\tTime Elapsed:\t" + watch.ElapsedMilliseconds.ToString("N0") + "ms"); | |
Console.WriteLine("\tCPU Cycles:\t" + cpuCycles.ToString("N0")); | |
// 5. | |
for (int i = 0; i <= GC.MaxGeneration; i++) | |
{ | |
int count = GC.CollectionCount(i) - gcCounts[i]; | |
Console.WriteLine("\tGen " + i + ": \t\t" + count); | |
} | |
Console.WriteLine(); | |
} | |
private static ulong GetCycleCount() | |
{ | |
ulong cycleCount = 0; | |
QueryThreadCycleTime(GetCurrentThread(), ref cycleCount); | |
return cycleCount; | |
} | |
[DllImport("kernel32.dll")] | |
[return: MarshalAs(UnmanagedType.Bool)] | |
private static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime); | |
[DllImport("kernel32.dll")] | |
private static extern IntPtr GetCurrentThread(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Examples | |
CodeTimer.Time("Thread Sleep", 1, () => Thread.Sleep(3000)); | |
CodeTimer.Time("Empty Method", 10000000, () => { }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment