linux应用中的时间处理

参考下:Linux下有关时间的函数:time,times,clock,gettimeofday等_linux time函数_见牛羊的博客-CSDN博客

下面的代码基本涵盖了获取时间和操作计时的一些函数使用:

#include "stdio.h"
#include "stdlib.h"
#include "time.h"
#include "sys/time.h"
#include  
#include 


int main(int argc, char *argv[])
{
    struct tm local_t;
    struct tm utc_t;
    time_t sec;
    char buf[100];
    struct timeval tval;
    struct tms tm_start,tm_end;
    clock_t ck_start, ck_end; 
    long tck;
    clock_t t_start,t_end;

    sec=time(NULL);
    if(-1 == sec)
    {
        perror("time");
        return -1;
    }
    printf("sec=%ld\n", sec);

    gettimeofday(&tval, NULL);
    printf("tval.tv_sec=%ld, tval.tv_usec=%ld\n", tval.tv_sec, tval.tv_usec);

    localtime_r(&sec, &local_t);
    gmtime_r(&sec, &utc_t);
    printf("localtime:%4d%02d%02d %02d:%02d:%02d\n", local_t.tm_year+1900, local_t.tm_mon, local_t.tm_mday,
                    local_t.tm_hour, local_t.tm_min, local_t.tm_sec);
    printf("utctime:%4d%02d%02d %02d:%02d:%02d\n", utc_t.tm_year+1900, utc_t.tm_mon, utc_t.tm_mday,
                    utc_t.tm_hour, utc_t.tm_min, utc_t.tm_sec);

    sec=mktime(&local_t);
    printf("mktime from localtime=%ld\n", sec);
    sec=mktime(&utc_t);
    printf("mktime from gmtime=%ld\n", sec);

    asctime_r(&local_t, buf);
    printf("localtime from asctime_r:%s", buf);
    asctime_r(&utc_t, buf);
    printf("utc time from asctime_r:%s", buf);

    strftime(buf, sizeof(buf), "%Y-%m-%d %A %H:%M:%S\n", &local_t);
    printf("localtime from strftime:%s", buf);
    strftime(buf, sizeof(buf), "%Y-%m-%d %A %H:%M:%S\n", &utc_t);
    printf("utc time from strftime:%s", buf);


    tck=sysconf(_SC_CLK_TCK);
    ck_start=times(&tm_start);
    t_start=clock();
    for(int i=0;i<200000;i++)
        getppid();
    sleep(1);
    ck_end=times(&tm_end);
    t_end=clock();
    printf("totaltime=%f\n", (ck_end-ck_start)/(double)tck);
    printf("user time=%f\n", (tm_end.tms_utime-tm_start.tms_utime)/(double)tck);
    printf("sys time=%f\n", (tm_end.tms_stime-tm_start.tms_stime)/(double)tck);
    printf("tck=%ld\n", tck);
    printf("totaltime from clock=%f\n", (t_end-t_start)/(double)CLOCKS_PER_SEC);
    printf("CLOCKS_PER_SEC=%ld\n", CLOCKS_PER_SEC);

    return 0;
}

你可能感兴趣的:(linux,linux,c++,vscode)