C#写一个高精度定时器

这篇文章是说明如何使用C#做高精度的计时器,有些时候,我们会需要用到精准度更高的计时器及Sleep,但Sleep的精准度并不高

因此只好自己客制化了

背景

在一般的系统中,Sleep(1)其实是相当于15.625ms(1/64秒),也就是说Sleep(15)以下都是Sleep一样的时间.

微软MSDN参考资料

源码

[c-sharp] view plain copy print ?
  1. [StructLayout(LayoutKind.Sequential)]
  2. public struct MSG
  3. {
  4. public IntPtr handle;
  5. public uint msg;
  6. public IntPtr wParam;
  7. public IntPtr lParam;
  8. public uint time;
  9. public System.Drawing.Point p;
  10. }
  11. public class AccurateTimer
  12. {
  13. public static bool IsTimeBeginPeriod = false;
  14. const int PM_REMOVE = 0x0001;
  15. [DllImport("kernel32.dll", SetLastError = true)]
  16. static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin,
  17. uint wMsgFilterMax, uint wRemoveMsg);
  18. [DllImport("kernel32.dll", SetLastError = true)]
  19. static extern bool TranslateMessage(ref MSG lpMsg);
  20. [DllImport("kernel32.dll", SetLastError = true)]
  21. static extern bool DispatchMessage(ref MSG lpMsg);
  22. [DllImport("kernel32.dll", SetLastError = true)]
  23. public static extern bool QueryPerformanceCounter(ref Int64 count);
  24. [DllImport("kernel32.dll", SetLastError = true)]
  25. public static extern bool QueryPerformanceFrequency(ref Int64 frequency);
  26. public static int GetTimeTick()
  27. {
  28. return Environment.TickCount;
  29. }
  30. public static void AccurateSleep(int a_i4MSec)
  31. {
  32. Int64 t_i8Frequency = 0;
  33. Int64 t_i8StartTime = 0;
  34. Int64 t_i8EndTime = 0;
  35. double t_r8PassedMSec = 0;
  36. MSG msg;
  37. AccurateTimer.QueryPerformanceCounter(ref t_i8StartTime);
  38. AccurateTimer.QueryPerformanceFrequency(ref t_i8Frequency);
  39. do
  40. {
  41. if (AccurateTimer.PeekMessage(out msg, IntPtr.Zero, 0, 0, PM_REMOVE))
  42. {
  43. AccurateTimer.TranslateMessage(ref msg);
  44. AccurateTimer.DispatchMessage(ref msg);
  45. }
  46. AccurateTimer.QueryPerformanceCounter(ref t_i8EndTime);
  47. t_r8PassedMSec = ((double)(t_i8EndTime - t_i8StartTime) / (double)t_i8Frequency) * 1000;
  48. } while (t_r8PassedMSec <= a_i4MSec);
  49. }
  50. }

说明

QueryPerformanceFrequency:可以取得每秒CPU的Performance Tick

QueryPerformanceCounter:可以取得CPU运行到现在的Tick数

在这个程式范例中,我自行写了一个AccurateSleep,这个函数的目的是因为Sleep的精准度只有15.625毫秒

如果只有计时器精准,但是Sleep却不精准,那怎么样也无法测出15.625毫秒以下的精准度

但是如果仅用while loop做等待,那却会造成程式无回应,因此在回圈中,需要再处理Windows的讯息,避免程式无回应

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值