#include<sys/time.h>intgettimeofday(structtimeval*tv,structtimezone*tz);// return 0 on success, -1 on error
structtimeval{time_ttv_sec;suseconds_ttv_usec;}
gettimeofday 可于 tv 指向的缓冲区中返回日历时间。
tz 参数是历史遗留,现已废弃,应始终设置为 NULL。
1
2
3
#include<time.h>time_ttime(time_t*timep);
time 返回自 Epoch 以来的秒数。
如果 timep 部位 NULL,还会将自 Epoch 以来的秒数置于 timep 所指向的位置
时间转换函数
1
2
3
#include<time.h>char*ctime(consttime_t*timep);
ctime 将返回一个长达 26 字节的字符串,内含标准格式的日期和时间。Sun Mar 13 20:31:58 2022
#if !defined(__sun)
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE
#endif
#endif
#include<time.h>#include<locale.h>#include"tlpi_hdr.h"#define SBUF_SIZE 1000
intmain(intargc,char*argv[]){structtmtm;charsbuf[SBUF_SIZE];char*ofmt;if(argc<3||strcmp(argv[1],"--help")==0)usageErr("%s input-date-time in-format [out-format]\n",argv[0]);if(setlocale(LC_ALL,"")==NULL)errExit("setlocale");/* Use locale settings in conversions */memset(&tm,0,sizeof(structtm));/* Initialize 'tm' */if(strptime(argv[1],argv[2],&tm)==NULL)fatal("strptime");tm.tm_isdst=-1;/* Not set by strptime(); tells mktime()
to determine if DST is in effect */printf("calendar time (seconds since Epoch): %ld\n",(long)mktime(&tm));ofmt=(argc>3)?argv[3]:"%H:%M:%S %A, %d %B %Y %Z";if(strftime(sbuf,SBUF_SIZE,ofmt,&tm)==0)fatal("strftime returned 0");printf("strftime() yields: %s\n",sbuf);exit(EXIT_SUCCESS);}
#include<sys/times.h>structtms{clock_ttms_utime;/* User CPU time. */clock_ttms_stime;/* System CPU time. */clock_ttms_cutime;/* User CPU time of dead children. */clock_ttms_cstime;/* System CPU time of dead children. */};clock_ttimes(structtms*buf);
times 检索进程时间信息,并把结果通过 buf 指向的结构体返回。tms 前两个字段返回调用进程到目前为止使用的用户和系统组件的 CPU 时间,后两个字段返回的信息是:父进程执行力系统调用 wait 的所有已经终止的子进程使用的 CPU 时间。
#include<sys/times.h>#include<time.h>#include"tlpi_hdr.h"/* Display 'msg' and process times */staticvoiddisplayProcessTimes(constchar*msg){structtmst;clock_tclockTime;staticlongclockTicks=0;if(msg!=NULL)printf("%s",msg);if(clockTicks==0){/* Fetch clock ticks on first call */clockTicks=sysconf(_SC_CLK_TCK);if(clockTicks==-1)errExit("sysconf");}clockTime=clock();if(clockTime==-1)errExit("clock");printf(" clock() returns: %ld clocks-per-sec (%.2f secs)\n",(long)clockTime,(double)clockTime/CLOCKS_PER_SEC);if(times(&t)==-1)errExit("times");printf(" times() yields: user CPU=%.2f; system CPU: %.2f\n",(double)t.tms_utime/clockTicks,(double)t.tms_stime/clockTicks);}intmain(intargc,char*argv[]){intnumCalls,j;printf("CLOCKS_PER_SEC=%ld sysconf(_SC_CLK_TCK)=%ld\n\n",(long)CLOCKS_PER_SEC,sysconf(_SC_CLK_TCK));displayProcessTimes("At program start:\n");/* Call getppid() a large number of times, so that
some user and system CPU time are consumed */numCalls=(argc>1)?getInt(argv[1],GN_GT_0,"num-calls"):100000000;for(j=0;j<numCalls;j++)(void)getppid();displayProcessTimes("After getppid() loop:\n");exit(EXIT_SUCCESS);}