QueryPerformance.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Runtime.InteropServices;
  7. namespace ServiceHelper
  8. {
  9. public class QueryPerformance
  10. {
  11. [DllImport("Kernel32.dll")]
  12. private static extern bool QueryPerformanceCounter(out long performanceCount);
  13. [DllImport("Kernel32.dll")]
  14. private static extern bool QueryPerformanceFrequency(out long frequency);
  15. private long begintTime = 0;//开始时间
  16. private long endTime = 0;//结束时间
  17. private long frequency = 0;//处理器频率
  18. public long BegintTime
  19. {
  20. get { return begintTime; }
  21. }
  22. public long EndTime
  23. {
  24. get { return endTime; }
  25. }
  26. public long Frequency
  27. {
  28. get { return frequency; }
  29. }
  30. public QueryPerformance()
  31. {
  32. QueryPerformanceFrequency(out frequency);//获取频率
  33. }
  34. public void Start()
  35. {
  36. QueryPerformanceCounter(out begintTime);
  37. }
  38. public string Stop(bool showRecord)
  39. {
  40. QueryPerformanceCounter(out endTime);
  41. if (showRecord)
  42. {
  43. return string.Format("用时:{0}ms", TastTime);
  44. }
  45. return null;
  46. }
  47. public double TastTime//花费时间:单位S
  48. {
  49. get
  50. {
  51. if (frequency > 0)
  52. return (double)(endTime - begintTime)*1000 / frequency;
  53. else
  54. return 0;
  55. }
  56. }
  57. }
  58. }