求科普:gettimeofday函数的使用
网上搜了获取系统时间的方法,搜了很久才查到用gettimeofday函数,但奈何网上搜到的资料比较复杂,里面涉及到的很多参数不太理解,搜到了以下几个例子,但不太理解里面的使用方法,不知道有没有大神能用简单易懂的方法讲下简单使用方法(本人萌新,尽量不要太复杂,理解会用就好)
程序代码:
#include <sys/time.h>
void f()
{
//...
}
int main()
{
struct timeval t1, t2;
gettimeofday(&t1, NULL);
f();
gettimeofday(&t2, NULL);
//那么函数f运行所花的时间为
//deltaT = (t2.tv_sec-t1.tv_sec) * 1000000 + t2.tv_usec-t1.tv_usec 微秒
return 0;
}
程序代码:
#include <sys/time.h>
#include <unistd.h>
main(){
struct timeval tv;
struct timezone tz;
gettimeofday (&tv, &tz);
printf("tv_sec; %d\n", tv.tv_sec);
printf("tv_usec; %d\n", tv.tv_usec);
printf("tz_minuteswest; %d\n", tz.tz_minuteswest);
printf("tz_dsttime, %d\n", tz.tz_dsttime);
}
程序代码:
#include<time.h>
#include<stdio.h>
#define MILLION 1000000
int main(void)
{
struct timespec tpstart;
struct timespec tpend;
long timedif;
gettimeofday(&tpstart, NULL);
gettimeofday(&tpend, NULL);
timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
fprintf(stdout, "it took %ld microseconds\n", timedif);
return 0;
}
有些地方需要大神讲解一下:例如第一第二个代码用<sys/time.h>第三个代码却用<time.h>不太理解二者有什么区别……还有,这三段代码有没有什么联系和区别?
能讲明白gettimeofday这个函数的简单用法就可以啦








