以下是全部代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
public static class CodeTimer
{
public static void Initialize()
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
}
public static void Time(String name, int interation, Action action)
{
ConsoleColor currentForeColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(name);
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Int32[] gcCounts = new Int32[GC.MaxGeneration + 1];
for (Int32 Incremental = 0; Incremental < gcCounts.Length; Incremental++)
gcCounts[Incremental] = GC.CollectionCount(Incremental);
Stopwatch watch = new Stopwatch(); watch.Start();
Int64 CycleCount = GetCycleCount();
for (Int32 Incremental = 0; Incremental < interation; Incremental++) action();
Int64 cpuCycles = GetCycleCount() - CycleCount;
watch.Stop();
Console.ForegroundColor = currentForeColor;
Console.WriteLine("/t执行时间:/t" + watch.ElapsedMilliseconds.ToString() + "毫秒");
Console.WriteLine("/tCPU时钟周期:/t" + cpuCycles.ToString());
for (Int32 Incremental = 0; Incremental < GC.MaxGeneration; Incremental++)
{
Int32 count = GC.CollectionCount(Incremental) - gcCounts[Incremental];
Console.WriteLine("/t" + Incremental + "代回收次数:/t" + count);
}
}
private static Int64 GetCycleCount()
{
Int64 n, kerneltime, usertime;
GetThreadTimes(GetCurrentThread(), out n, out n, out kerneltime, out usertime);
return kerneltime + usertime;
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetThreadTimes(IntPtr hThread,
out long lpCreationTime,
out long lpExitTime,
out long lpKernelTime,
out long longlpUserTime);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
}
}
如下测试:
CodeTimer.Initialize();
String strTestOne = String.Empty;
CodeTimer.Time("String Concat", 100000, () => { strTestOne += "a"; });
StringBuilder strTestTwo = new StringBuilder(100000);
CodeTimer.Time("StringBuilder", 100000, () => { strTestTwo.Append("a"); });
Console.Read();