C语言中获取时间记录

来源:互联网 发布:紫金桥软件 编辑:程序博客网 时间:2024/05/21 10:20

最近在网络上找了一个CPU和GPU矩阵乘法对比的demo(http://www.cnblogs.com/stormhan/p/5467187.html)
在Linux中运行,一直报错
error: identifier "GetTickCount" is undefined
这是因为GetTickCount是Windows中的函数,需要引入头文件windows.h,当然,在Linux中这种方法并不适用。这就需要我们了解GetTickCount的作用,找到Windows中GetTickCount()在Linux中的替代函数。

经过查询得到,GetTickCount是记录时间的,返回自设备启动后的毫秒数,用法为

 Start:=GetTickCount;    ...//执行耗时的操作    Stop:=GetTickCount;    TimeUsed:=(Stop-Start)/1000;     //使用了xxx秒

(参考http://www.cnblogs.com/jxsoft/archive/2011/10/17/2215366.html)

这就需要找到Linux中记录时间的方法。C语言中有多种方法可以实现,例如clock()、times()、clock_gettime()、gettimofday(),但是不同方法是有差别的
clock()函数的精确度是10毫秒(ms)
times()函数的精确度是10毫秒(ms)
gettimofday()函数的精确度是微秒(μs)
clock_gettime()函数的计量单位为十亿分之一,也就是纳秒(ns)
参考http://www.cnblogs.com/krythur/archive/2013/02/25/2932647.html

我使用的方法是clock_gettime(),用法为

struct timespec tpstart;struct timespec tpend;long timedif;//unsigned int tick1 = GetTickCount();clock_gettime(CLOCK_MONOTONIC, &tpstart);...//执行耗时的操作   clock_gettime(CLOCK_MONOTONIC, &tpend);timedif = 1000*(tpend.tv_sec - tpstart.tv_sec) + (tpend.tv_nsec - tpstart.tv_nsec)/1000000;printf("use time : %ldms\n",timedif);
0 0