Net 实现纳秒级别计算

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); } /*-------------------------------------------------------------------------------------------
原文地址:https://www.cnblogs.com/mikelij/p/1779857.html