High-Performance Timer in C#

来源:互联网 发布:怎么看有没有网络监控 编辑:程序博客网 时间:2024/04/27 14:43

继上一篇 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();        }






1 0