High-Performance Timer in C#

继上一篇 http://blog.csdn.net/Joyhen/article/details/17222273

原文:http://www.codeproject.com/Articles/2635/High-Performance-Timer-in-C

上码:

namespace ConsoleApplication1
{
    using System;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.Threading;

    internal class HiPerfTimer
    {
        const string dll = "Kernel32.dll";

        [DllImport(dll)]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

        [DllImport(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;
            }
        }
    }
}
使用:

static void Main(string[] args)
        {
            HiPerfTimer pt = new HiPerfTimer();
            pt.Start();

            var items = Guid.NewGuid();
            Console.WriteLine(items.ToString());

            pt.Stop();

            Console.WriteLine("Duration: {0} sec\n", pt.Duration);

            Console.ReadKey();
        }






你可能感兴趣的:(KERNEL32.dll,stopwatch,HiPerfTimer)