using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace Zhaizj.Framework { /// /// 秒表,用于测试程序耗时 /// public class Stopwatch { private Boolean _IsStop; private long frequency; private decimal multiplier = 1000000000M; private long start; private long stop; [DllImport( "KERNEL32" )] private static extern Boolean QueryPerformanceCounter( out long lpPerformanceCount ); [DllImport( "Kernel32.dll" )] private static extern Boolean QueryPerformanceFrequency( out long lpFrequency ); public Stopwatch() { if (!QueryPerformanceFrequency( out this.frequency )) { throw new Win32Exception(); } } /// /// 开始启动 /// public void Start() { this._IsStop = false; QueryPerformanceCounter( out this.start ); } /// /// 停止 /// public void Stop() { if (!this._IsStop) { QueryPerformanceCounter( out this.stop ); this._IsStop = true; } } /// /// 总共耗时(毫秒) /// public double ElapsedMilliseconds { get { double result = this.getDuration() / 1000000.0; if (result < 0) result = 0; return result; } } /// /// 总共耗时(秒) /// public double ElapsedSeconds { get { double result = this.ElapsedMilliseconds / 1000.0; if (result < 0) result = 0; return result; } } private double getDuration() { return (((this.stop - this.start) * ((double)this.multiplier)) / ((double)this.frequency)); } } }