2011-04-01 11:12:52| 分类:
C#.Net | 标签:
timer |字号
在C#中简单的计时可以使用DateTime类,该类提供的方法可以得到精确到秒的数据,不过想要再得到更精确时间就无能为力了。但是并不表示C#就没办法,其实实现起来也很简单。
第一种方法是使用System.Diagnostics命名空间下的Stopwatch 类,该类是.NET Framework 2.0中新增的,它提供一组方法和属性,可用于准确地测量运行时间,使用起来很简单,无非是实例化对象,调用方法和属性。
System.Diagnostics.Stopwatch MyWatch = new System.Diagnostics.Stopwatch();
MyWatch.Start();
for (int i = 0; i < Int16.MaxValue; i++)
{
string st = string.Format("%d", i);
}
MyWatch.Stop();
Console.WriteLine(MyWatch.ElapsedMilliseconds.ToString());
另外一种方法是自己编写一个类,如下: class HPTimer
{
//引用系统API
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
private static long StartTime, StopTime;
private static long Frequence;
public HPTimer()
{
StartTime = 0;
StopTime = 0;
if (QueryPerformanceFrequency(out Frequence) == false)
throw new Win32Exception();
}
public void Start()
{
QueryPerformanceCounter(out StartTime);
}
public void Stop()
{
QueryPerformanceCounter(out StopTime);
}
public double Duration
{
get{return 1000*(double)(StopTime - StartTime) /(double)Frequence;}
}
}
同样通过调用该类也可以实现,测试表示后一种方法比较好,因为如果不足1毫秒的话,前者返回0
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。