高效能 計時器:統計功能耗時
阿新 • • 發佈:2020-07-20
/// <summary> /// 高效能 計時器:統計功能耗時ms /// </summary> public class HiPerfTimer { [System.Security.SuppressUnmanagedCodeSecurity] [System.Runtime.InteropServices.DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter(out long lpPerformanceCount); [System.Security.SuppressUnmanagedCodeSecurity] [System.Runtime.InteropServices.DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency(out long lpFrequency); private long startTime; // start time, in cpu ticks private long stopTime; // stop time, in cpu ticks private long freq; // CPU frequency, ticks per second public HiPerfTimer() { startTime = 0; stopTime = 0; if (false == QueryPerformanceFrequency(out freq)) { throw new System.ComponentModel.Win32Exception(); // high-performance counter not supported } } public void Start() { System.Threading.Thread.Sleep(0); QueryPerformanceCounter(out startTime); } public void Stop() { QueryPerformanceCounter(out stopTime); } /// <summary> /// 間隔(ms) /// </summary> public double Duration { get { return (double)(stopTime - startTime) / (double)freq * 1000; } } }