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);
}
/*——————————————————————————————-
