|
Public static class CodeTimer
{
Private static bool isQueryThreadCycleTime = false;
Public static void Initialize ()
{
Process. GetCurrentProcess (). PriorityClass = ProcessPriorityClass. High;
Thread. CurrentThread. Priority = ThreadPriority. Highest;
If (Environment. OSVersion. Platform = PlatformID. Win32NT & Environment. OSVersion. Version. Major> = 6)
{
IsQueryThreadCycleTime = true;
}
Time ("", 1, () => {});
}
Public static void Time (string name, int iteration, Action action)
{
If (String. IsNullOrEmpty (name) return;
// Warm up
Action ();
// 1.
Lelecolor 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 + ": tt" + count );
}
Console. WriteLine ();
}
Private static ulong GetCycleCount ()
{
Ulong cycleCount = 0;
If (isQueryThreadCycleTime)
{
QueryThreadCycleTime (GetCurrentThread (), ref cycleCount );
}
Else
{
Ulong l;
Ulong kernelTime, userTimer;
GetThreadTimes (GetCurrentThread (), out l, out l, out kernelTime,
Out userTimer );
CycleCount = kernelTime + userTimer;
}
Return cycleCount;
}
[DllImport ("kernel32.dll")]
[Return: financialas (UnmanagedType. Bool)]
Static extern bool QueryThreadCycleTime (IntPtr threadHandle, ref ulong cycleTime );
[DllImport ("kernel32.dll")]
Static extern IntPtr GetCurrentThread ();
[DllImport ("kernel32.dll", SetLastError = true)]
Static extern bool GetThreadTimes (IntPtr hThread, out ulong lpCreationTime,
Out ulong lpExitTime, out ulong lpKernelTime, out ulong lpUserTime );
} |