High-Performance Timer in C#

亦凉 2022-08-02 14:48 337阅读 0赞

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

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

上码:

  1. namespace ConsoleApplication1
  2. {
  3. using System;
  4. using System.Runtime.InteropServices;
  5. using System.ComponentModel;
  6. using System.Threading;
  7. internal class HiPerfTimer
  8. {
  9. const string dll = "Kernel32.dll";
  10. [DllImport(dll)]
  11. private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
  12. [DllImport(dll)]
  13. private static extern bool QueryPerformanceFrequency(out long lpFrequency);
  14. private long startTime, stopTime;
  15. private long freq;
  16. // Constructor
  17. public HiPerfTimer()
  18. {
  19. startTime = 0;
  20. stopTime = 0;
  21. if (QueryPerformanceFrequency(out freq) == false)
  22. {
  23. // high-performance counter not supported
  24. throw new Win32Exception();
  25. }
  26. }
  27. // Start the timer
  28. public void Start()
  29. {
  30. // lets do the waiting threads there work
  31. Thread.Sleep(0);
  32. QueryPerformanceCounter(out startTime);
  33. }
  34. // Stop the timer
  35. public void Stop()
  36. {
  37. QueryPerformanceCounter(out stopTime);
  38. }
  39. // Returns the duration of the timer (in seconds)
  40. public double Duration
  41. {
  42. get
  43. {
  44. return (double)(stopTime - startTime) / (double) freq;
  45. }
  46. }
  47. }
  48. }

使用:

  1. static void Main(string[] args)
  2. {
  3. HiPerfTimer pt = new HiPerfTimer();
  4. pt.Start();
  5. var items = Guid.NewGuid();
  6. Console.WriteLine(items.ToString());
  7. pt.Stop();
  8. Console.WriteLine("Duration: {0} sec\n", pt.Duration);
  9. Console.ReadKey();
  10. }

SouthEast

发表评论

表情:
评论列表 (有 0 条评论,337人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C# Timer:定时器控件

             Timer不直接显示在窗体上,和其它控件连用,表示每隔一段时间执行一次Tick事件           定时器控件中常用的属性是Interval,用于设置时

    相关 C++ boost timer

    boost库中的timer类能够为程序员提供毫秒级别的操作精度和操作函数,它是一个小型的计时器,可以用来测量时间的流逝。 timer类位于boost命名空间下,使用时需要包含