[笔记]linux C/C++ 获取精确时间方法

1.linux获取带毫秒的时间

#include 
#include 
//调用函数时候可以传入字符串进行区别和标记
void sysUsecTime(const char *a)
{
    struct timeval tv;
    struct timezone tz;
    struct tm *p;
    gettimeofday(&tv, &tz);
    p = localtime(&tv.tv_sec);
    os_printf("%s:%04d-%02d-%02d-%02d-%02d-%02d-%06ld\n",a,1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, tv.tv_usec);
}

运行结果

[笔记]linux C/C++ 获取精确时间方法_第1张图片

 

2.win32和linux获取带毫秒的时间来计算时间差

#include 
#ifndef WIN32
 #include 
#endif

double time_get()
{
    time_t time_sec;
    double nowtime=0;
    time_sec = time(NULL);
#ifdef WIN32
    struct	timeb	tp;
    ftime(&tp);
    nowtime=time_sec*1000+tp.millitm;
    printf( "time: %f\n", nowtime );
#else
    struct timeval tmv;
    gettimeofday(&tmv, NULL);
    nowtime=time_sec*1000+tmv.tv_usec/1000;
    printf( "time: %f\n", nowtime );
#endif
    return nowtime;
}

int main()
{
    double start,end,duration;
    start = time_get();
    sleep(3);
    end = time_get();
    duration = (end - start)/1000;
    printf( "%f seconds\n", duration );
    return 0;
}

计算两个时间差就开始和结束都调用time_get()获取时间,然后相减除以1000即可

duration = (double)(finish_time - start_time) / 1000;

你可能感兴趣的:(笔记,c获取时间,毫秒,time.h,linux获取时间)