zoukankan      html  css  js  c++  java
  • 高性能定时器(转自codeproject)

    看了这篇文章,

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

    很不错的方法,虽然平时很少用到这么精确的定时器,但是这里我产生了一个想法,可以使用这个定时器,

    用途:

    1、 验证算法(code)执行的效率(时间上)

    2、用于某些控制场合,比如需要对精确的时间周期

    high-performance timer  class:

    /// <summary>
        /// A C# class to provide exact time measurement in your applications.
        /// craigtao : 可以用来验证算法的效率如何
        /// </summary>
        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;
    
            public HiPerfTimer()
            {
                startTime = 0;
                stopTime = 0;
    
                if (QueryPerformanceFrequency(out freq) == false)
                {
                    // high-PerformanceFrequency 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);
            }
    
            //return the dutation of the timer (seconds)
            public double Duration
            {
                get
                {
                    return (double)(stopTime - startTime) / (double)freq;
                }
            }
        }

    测试使用:

    class Program
        {
            static void Main(string[] args)
            {
                HiPerfTimer pt = new HiPerfTimer(); // create a new PerfTimer object
                pt.Start();
    
                //the code time
                Console.WriteLine("Jesus loves you!
    ");
                Console.WriteLine("Jesus loves you!, you know? 
    ");
    
                pt.Stop();
    
                Console.WriteLine("Duration:{0} sec
    ",
                    pt.Duration);
    
                Console.ReadKey();  // for remain console windows
            }
        }

    效果:

  • 相关阅读:
    易经03
    易经02
    易经01
    机器学习Ng-01
    离散数学-01
    新概念4-21
    新概念4-20
    新概念4-19
    nefu 120 Lucas-Lehmer 梅森素数判别法
    nefu 120 Lucas-Lehmer 梅森素数判别法 二分-大数乘法换加法
  • 原文地址:https://www.cnblogs.com/craigtao/p/4553759.html
Copyright © 2011-2022 走看看