一个大前提是需要系统硬件支持,似乎我遇到的大多数系统都是支持的。在Linux下,使用gettimeofday函数。函数的声明如下:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv , const struct timezone *tz);
而参数 struct timeval *tv 的定义如下:
struct timeval {
long tv_sec; /* 秒 */
long tv_usec; /* 微秒(1e-6秒) */
};
第二个参数暂无效,设置成NULL即可。例子:
struct timeval t_start, t_end;
gettimeofday(&t_start, NULL);
foo();
gettimeofday(&t_end, NULL);
printf("Time consumed by function \"foo()\" is %d macroseconds\n",
(t_end.tv_sec - t_start.tv_sec) * 1000000 +
(t_end.tv_usec - t_start.tv_usec));
详细介绍可以参考http://linuxreviews.org/man/gettimeofday/index.html.en.
而在Win32下,类似功能可使用GetTickCount()实现,但精度只到毫秒。