【IT168技术文档】
using System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Threading; internal class HiPerfTimer { [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter( out long lpPerformanceCount); [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency( out long lpFrequency); private long startTime, stopTime; private long freq; // Constructor public HiPerfTimer() { startTime = 0; stopTime = 0; if (QueryPerformanceFrequency(out freq) == false) { // high-performance counter not supported throw new Win32Exception(); } } // Start the timer public void Start() { // lets do the waiting threads there work Thread.Sleep(0); QueryPerformanceCounter(out startTime); } // Stop the timer public void Stop() { QueryPerformanceCounter(out stopTime); } // Returns the duration of the timer (in seconds) public double Duration { get { return (double)(stopTime - startTime) / (double) freq; } } } } using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Threading; namespace ConsoleApplication1 { class Program { [DllImport("kernel32.dll")] private static extern bool QueryPerformanceFrequency(ref Int64 lpFrequency); [DllImport("kernel32.dll")] private static extern bool QueryPerformanceCounter(ref Int64 lpPerformanceCount); public static void Main(string[] args) { //long time; //time = DateTime.Now.Ticks; //Console.WriteLine(time); long frequency = 0; if (!QueryPerformanceFrequency(ref frequency)) { Console.WriteLine("not supported."); return; } long start = 0; if (!QueryPerformanceCounter(ref start)) { Console.WriteLine("query start failed."); return; } Thread.Sleep(1000); long end = 0; if (!QueryPerformanceCounter(ref end)) { Console.WriteLine("query end failed."); return; } Console.WriteLine("frequency = {0}, total time {1}", frequency, (double)(end - start) / ((double)frequency)); } } }