C#中获取精确时间
2011-12-10 21:21
309 查看
程序中获取精确的时间,有时是非常必要的。常用的是,在测试程序的性能时,需要使用到精确的时间计时。或者其他情况要用到精确的时间。这就要用到一个函数QueryPerformanceCounter()。用法是从第一次调用QueryPerformanceCounter(),过一段时间后再次调用该函数结束的.两者之差除以QueryPerformanceFrequency()的频率就是开始到结束之间的秒数。由于计时函数本身是要耗费很少的时间,所以但一般忽略不计。
有一点要注意的是,如果在多处理器的电脑上使用这个函数需要,需要指定调用的处理器。因为在不同的处理器上会得到不同的结果。
下面的类可以实现该功能。
有一点要注意的是,如果在多处理器的电脑上使用这个函数需要,需要指定调用的处理器。因为在不同的处理器上会得到不同的结果。
下面的类可以实现该功能。
public class QueryPerformance { [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter(out long performanceCount); [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency(out long frequency); private long begintTime = 0;//开始时间 private long endTime = 0;//结束时间 private long frequency= 0;//处理器频率 public long BegintTime { get{return begintTime;} } public long EndTime { get{return endTime;} } public long Frequency { get{return frequency;} } public QueryPerformance() { QueryPerformanceFrequency(frequency)//获取频率 } public void Start() { QueryPerformanceCounter(begintTime); } public void Stop(bool showRecord) { QueryPerformanceCounter(endTime); if (showRecord) { Console.WriteLing(string.Format("用时:{0}s", TastTime)); } } public double TastTime//花费时间:单位S { get { if(frequency>0) return (double)(endTime - begintTime) / frequency; else return 0; } } }调用:
QueryPerformance queryPerformance = new QueryPerformance(); QueryPerformance.Start(); //代码块、函数等 QueryPerformance.Stop(true);本文出自 “西北白杨树” 博客,请务必保留此出处http://yangyoushan.blog.51cto.com/7229571/1276601
相关文章推荐
- C#中获取精确时间
- C#获取代码执行时间(精确到毫秒)
- 获取C#代码执行的时间(精确到毫秒)
- 获取C#代码执行的时间(精确到毫秒)
- 获取C#代码执行的时间(精确到毫秒)
- C#获取网络日期时间
- c#.net 获取时间年月日时分秒格式
- 在windows平台下获取精确经过时间
- c#获取当前日期时间
- C++ 获取程序运行时间/时间戳 精确到毫秒
- 获取时间C#、Java
- c# 获取时间戳
- 获取系统时间的几种方法,最高精确1ms
- asp.net c# 打开新页面或页面跳转&&获取时间
- VC++ 获取系统时间、程序运行时间(精确到秒,毫秒)的五种方法
- c#获取当前系统的时间
- VC获取系统时间、程序运行时间(精确到秒,毫秒)的五种方法
- C# 根据当前时间获取,本周,本月,本季度等时间段
- C#获取当前日期时间
- C#中的系统时间获取问题