1)建立VC.NET 托管類庫
using namespace System;
namespace MLTimerDot
{
//得到計算機啟動到現在的時鐘周期
unsigned __int64 GetCycleCount(void)
_asm _emit 0x0F
_asm _emit 0x31
}
//聲明 .NET 類
public __gc class MLTimer
protected:
UInt64 m_startcycle;
UInt64 m_overhead;
public:
MLTimer(void)
//為了計算更精确取得調用一個 GetCycleCount() 的時鐘周期
m_overhead=0;
Start();
m_overhead=Stop();
//計算停止
UInt64 Stop(void)
return GetCycleCount()-m_startcycle-m_overhead;
//計算開始
void Start(void)
m_startcycle=GetCycleCount();
__property virtual UInt64 get_Overhead()
return m_overhead;
};
2)測試代碼
//C# 引用後放一個Button 測試
private void button1_Click(object sender, System.EventArgs e)
MLTimerDot.MLTimer timer=new MLTimerDot.MLTimer();
timer.Start();
Thread.Sleep(1000);
UInt64 cpuspeed10=(ulong)(timer.Stop()/100000); //通過這個可以算出 CPU 的mhz
timer.Start();//開始
//測試代碼(測試聲明一個DataTable 用的時間)
DataTable td= new DataTable();
UInt64 time1=timer.Stop();//停止
String s= String.Format("CPU {0}.{1} mhz\n聲明 MLTimer 類的系統開銷 {2:n} 時鐘周期\n本作業系統開銷 {3:n} 個時鐘周期\n使用 {4:n} ns",
cpuspeed10/10,cpuspeed10%10,timer.Overhead,
time1,
time1*10000/cpuspeed10);
MessageBox.Show(s);
/*-------------------------------------------------------------------------------------------