linux中的gettimeofday方法

Posted on 2020-04-28 10:53  yacbo  阅读(1473)  评论(0编辑  收藏  举报
测试调用delya()函数所需执行的时间(单位为微妙)
#include<stdio.h>
#include<sys/time.h>
#include<unistd.h>
int delay(int time)
{
    int i,j;
    for(i =0;i<time;i++)
        for(j=0;j<5000;j++)
            ;
}

int main()
{
        struct  timeval start;
        struct  timeval end;
        unsigned  long diff;
        gettimeofday(&start,NULL);
        delay(10);
        gettimeofday(&end,NULL);
        diff = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec;
        printf(“thedifference is %ld\n”,diff);
        return 0;
}

 

linux中获取字符串时间

string get_local_time()
{
    char time_str[60]={0};
    struct timeval tvpre;
    gettimeofday(&tvpre, NULL);
    struct tm* ptm;
    char time_string[40];
    long milliseconds;
    ptm = localtime (&(tvpre.tv_sec));
    /* 格式化日期和时间,精确到秒为单位。*/
    //strftime (time_string, sizeof(time_string), "%Y/%m/%d %H:%M:%S", ptm); //输出格式为: 2018/12/09 10:48:31.391
    //strftime (time_string, sizeof(time_string), "%Y|%m|%d %H-%M-%S", ptm); //输出格式为: 2018|12|09 10-52-28.302
    strftime (time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm); //输出格式为: 2018-12-09 10:52:57.200
    //strftime (time_string, sizeof(time_string), "%Y\\%m\\%d %H-%M-%S", ptm); //输出格式为: 2018\12\09 10-52-28.302
    /* 从微秒计算毫秒。*/
    milliseconds = tvpre.tv_usec / 1000;
    /* 以秒为单位打印格式化后的时间日期,小数点后为毫秒。*/
    snprintf (time_str, sizeof(time_str), "%s.%03ld", time_string, milliseconds);
    return string(time_str);
}
string GetSystemTime()
{
    time_t timep;time (&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep));
    string s(tmp);
    return s;
}

 

Copyright © 2024 yacbo
Powered by .NET 8.0 on Kubernetes