time的使用

来源:互联网 发布:linux语言切换 编辑:程序博客网 时间:2024/06/03 21:02

时间函数使用如time,ctime,gmtime_r,localtime_r,gettimeofday,还有一个sysinfo,可以获取开机之后的秒数,更多的可以查看sysinfo结构体

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#include <sys/time.h>int main(int argc, char const *argv[]){    time_t time_t1 = -1;    struct tm tm1;    struct timeval timeval1;    time_t1 = time(NULL);                      //获取1970年至今的秒数    printf("time_t1 = %ld\n", time_t1);    printf("ctime: %s\n", ctime(&time_t1));   //把秒数转换为日历时间calender time    memset(&tm1, 0, sizeof(tm1));    gmtime_r(&time_t1, &tm1);                 //把秒数转换为UTC时间     printf("utc hour = %d\n", tm1.tm_hour);    memset(&tm1, 0, sizeof(tm1));   localtime_r(&time_t1, &tm1);               //把秒数转换为本地时间    printf("local hour = %d\n", tm1.tm_hour);    memset(&timeval1, 0, sizeof(timeval1));    gettimeofday(&timeval1, NULL);           //获取1970年至今的秒数和微秒数    printf("sec = %ld, usec = %ld\n", timeval1.tv_sec, timeval1.tv_usec);    sysinfo(&sysinfo1);    printf("boot time = %ld\n", sysinfo1.uptime);  //开机到目前为止经过的秒数    return 0;}out:time_t1 = 1506002179ctime: Thu Sep 21 21:56:19 2017utc hour = 13local hour = 21sec = 1506002179, usec = 157858boot time = 1137

tm结构体和sysinfo结构体:

           struct tm {               int tm_sec;    /* Seconds (0-60) */               int tm_min;    /* Minutes (0-59) */               int tm_hour;   /* Hours (0-23) */               int tm_mday;   /* Day of the month (1-31) */               int tm_mon;    /* Month (0-11) */               int tm_year;   /* Year - 1900 */               int tm_wday;   /* Day of the week (0-6, Sunday = 0) */               int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */               int tm_isdst;  /* Daylight saving time */           }; struct sysinfo {               long uptime;             /* Seconds since boot */               unsigned long loads[3];  /* 1, 5, and 15 minute load averages */               unsigned long totalram;  /* Total usable main memory size */               unsigned long freeram;   /* Available memory size */               unsigned long sharedram; /* Amount of shared memory */               unsigned long bufferram; /* Memory used by buffers */               unsigned long totalswap; /* Total swap space size */               unsigned long freeswap;  /* swap space still available */               unsigned short procs;    /* Number of current processes */               char _f[22];             /* Pads structure to 64 bytes */           };

原创粉丝点击