//应用程序执行时间监测器-IntervalTimer
---------------------------------------------
空间限制,删除了注释!!
---------------------------------------------
using System;
using System.Runtime.InteropServices;
namespace ymz.IntervalTimer
{
public class IntervalTimer
{
#region API调用
[DllImport("kernel32.dll")]
static extern private int QueryPerformanceCounter(out long counter);
[DllImport("kernel32.dll")]
static extern private int QueryPerformanceFrequency(out long counter);
#endregion
#region 内部变量
private TimerState state;
private long ticksAtStart;
private long intervalTicks;
private static long frequency;
private static int decimalPlaces;
private static string formatString;
private static bool initialized = false;
#endregion
public IntervalTimer()
{
if(! initialized)
{
QueryPerformanceFrequency(out frequency);
decimalPlaces = (int)Math.Log10(frequency);
// 根据频率的精确度设置当前平台的小数位数
formatString = String.Format("interval : {{0:F{0}}} seconds ({{1}}ticks)",decimalPlaces);
initialized = true;
}
state = TimerState.NotStarted;
}
public void Start()
{
state = TimerState.Started;
QueryPerformanceCounter(out ticksAtStart);
}
public void Stop()
{
long current;
QueryPerformanceCounter(out current);
intervalTicks = current - ticksAtStart;
state = TimerState.Stopped;
}
public float GetSeconds()
{
if(state != TimerState.Stopped)
throw new TimerNotStoppedException();
return (float)intervalTicks / (float)frequency;
}
public long GetIntervalTicks()
{
if(state != TimerState.Stopped)
throw new TimerNotStoppedException();
return intervalTicks;
}
public override string ToString()
{
if(state != TimerState.Stopped)
return "Interval timer, state : " + state.ToString();
else
return String.Format(formatString, GetSeconds(), intervalTicks);
}
}
public enum TimerState
{
NotStarted,
Stopped,
Started
}
public class TimerNotStoppedException : System.ApplicationException
{
public TimerNotStoppedException()
: base("Timer is either still running or has not been started.")
{
}
}
}
评论