突然要用到C程序里调用当前时间,来测试一段代码的运行时间。找了一下是否有可以调用的库函数,没想到真的有:gettimeofday。因为这里的这个应用蛮常用的,所以留个记录在此。
#include <stdio.h>
#include <stdlib.h>
struct timeval
{
long tv_sec; /* 秒数 */
long tv_usec; /* 微秒数 */
};
struct timezone
{
int tv_minuteswest;
int tv_dsttime;
};
int gettimeofday(struct timeval *tv,struct timezone *tz);
void function()
{
// function to run some time consuming codes
}
int main(int argc, char *argv[])
{
struct timeval tpstart,tpend;
float timespend;
gettimeofday(&tpstart,NULL);
function();
gettimeofday(&tpend,NULL);
timespend = tpend.tv_sec - tpstart.tv_sec;
printf("Time Spend: %d", timespend);
return EXIT_SUCCESS;
}