The Linux Programming Interface 10 Time 时间

本文介绍了Linux编程接口中关于时间的概念,如实际时间与进程时间,并详细讲解了gettimeofday()、time()、ctime()、gmtime()、localtime()、mktime()等时间函数的用法。通过示例程序展示了如何获取和处理时间,包括时间戳、本地化和进程时间。最后,讨论了时区和进程时间信息的获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Linux Programming Interface

Time

(01) 实际时间和进程时间概念

Real time: This is the time as measured either from some standard point (calendar time) or from some fixed point (typically the start) in the life of a process (elapsed or wall clock time).

Process time: This is the amount of CPU time used by a process. Measuring process time is useful for checking or optimizing the performance of a program or algorithm.

(02)gettimeofday()函数

The gettimeofday() system call returns the calendar time in the buffer pointed to by tv.

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);

struct timeval {

    time_t tv_sec;                 /* Seconds since 00:00:00, 1 Jan 1970 UTC */

    suseconds tv_usec;      /* Additional microseconds (long int) */

}

tz argument is now obsolete and should always be specified as NULL.

(03) time函数

The time() system call returns the number of seconds since the Epoch

#include <time.h>

time_t time(time_t *timep);

(04)时间转换函数

(05) ctime() 函数

The ctime() function provides a simple method of converting a time_t value into printable form.

char *ctime(const time_t *timep);

(06)写一个简单的程序打印当前的时间

  1 #include <stdio.h>
  2 #include <sys/time.h>
  3 #include <time.h>
  4 
  5 int main() {
  6      time_t timep;
  7      struct tm *p;
  8      time(&timep);
  9      p = localtime(&timep);
 10      printf("%d-%d-%d %d:%d:%d\n",
 11         (1900 + p->tm_year), (1 + p->tm_mon),
 12         p->tm_mday, (p->tm_hour + 12), p->tm_min, p->tm_sec);
 13     return 0;
 14 }

输出:

wang@wang:~/srccode/yunos$ ./timeprint
2017-3-9 25:48:22

(07) gmtime() 和localtime()函数

The gmtime() and localtime() functions convert a time_t value into a so-call broken down time. The broken-down time is placed in a statically allocated structure whose address is returned as the function result.

struct tm *gmtime(const time_t *timep);                /* Greenwich Mean Time */

struct tm *localtime(const time_t *timep);            

struct tm {
    int tm_sec;		/* second (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 since 1900 */
    int tm_wday;	/* day of the week (sunday = 0) */
    int tm_yday;	/* day in the year (0-365) */
    int tm_isdst;	/* daylight saving time flag */
};

(08) mktime() function

The mktime() function translates a broken-down time, expressed as local time, into a time_t value, which is returned as the function result.

(09)时间程序举例

#include <locale.h>
#include <time.h>
#include <sys/time.h>
#include "tlpi_hdr.h"

/* tropical 赤道 */
#define SECONDS_IN_TROPICAL_YEAR (365.24219 * 24 * 60 * 60)

int main(int argc, char *argv[]) {
	time_t t;
	struct tm *gmp, *locp;
	struct tm gm, loc;
	struct timeval tv;

	t = time(NULL);
	printf("Seconds since the Epoch (1 Jan 1970): %ld", (long) t);
	printf(" (about %6.3f years)\n", t / SECONDS_IN_TROPICAL_YEAR);

	if (gettimeofday(&tv, NULL) == -1)
		errExit("gettimeofday");
	printf(" gettimeofday() return %ld secs, %ld microsecs\n",
		(long) tv.tv_sec, (long) tv.tv_usec);

	gmp = gmtime(&t);
	if (gmp == NULL)
		errExit("gmtime");
	
	/* Save local copy, since *gmp may be modified by asctime(), or gmtime() */
	gm = *gmp;

	printf("Broken down by gmtime():\n");
	printf(" year = %d mon = %d mday = %d hour = %d min = %d sec = %d ",
		gm.tm_year, gm.tm_mon, gm.tm_mday, gm.tm_hour, gm.tm_min, gm.tm_sec);
	printf("wday = %d yday = %d isdst = %d\n", gm.tm_wday, gm.tm_yday, gm.tm_isdst);

	locp = localtime(&t);
	if (locp == NULL)
		errExit("localtime");
	
	/* save local copy */
	loc = *locp;
	printf("Broken down by localtime():\n");
	printf("	year = %d, mon = %d, mday = %d, hour = %d, min = %d, sec = %d, ",
		loc.tm_year, loc.tm_mon, loc.tm_mday, loc.tm_hour, loc.tm_min, loc.tm_sec);
	printf("wday = %d, yday = %d isdst = %d\n\n",
		loc.tm_wday, loc.tm_yday, loc.tm_isdst);
	
	printf("asctime() formats the gmtime() value as: %s", asctime(&gm));
	printf("ctime() formats the time() value as: 	%s", ctime(&t));

	printf("mktime() of gmtime() value: %ld secs\n", (long)mktime(&gm));
	printf("mktime() of localtime() value: %ld secs\n", (long)mktime(&loc));

	exit(EXIT_SUCCESS);
}
输出:

wang@wang:~/test/tlpi-dist/lib$ ./calendar_time
Seconds since the Epoch (1 Jan 1970): 1489050881 (about 47.186 years)
 gettimeofday() return 1489050881 secs, 744193 microsecs
Broken down by gmtime():
 year = 117 mon = 2 mday = 9 hour = 9 min = 14 sec = 41 wday = 4 yday = 67 isdst = 0
Broken down by localtime():
    year = 117, mon = 2, mday = 9, hour = 17, min = 14, sec = 41, wday = 4, yday = 67 isdst = 0

asctime() formats the gmtime() value as: Thu Mar  9 09:14:41 2017
ctime() formats the time() value as:     Thu Mar  9 17:14:41 2017
mktime() of gmtime() value: 1489022081 secs
mktime() of localtime() value: 1489050881 secs

(10)时区

这些时间的显示上面的东西,具体需要用的时候查手册就可以了,不要什么时间去记忆,懂得使用其中简单的就行。

  1 #include <time.h>
  2 #include <locale.h>
  3 #include "tlpi_hdr.h"
  4 
  5 #define BUF_SIZE 200
  6 
  7 int main(int argc, char *argv[]) {
  8     time_t t;
  9     struct tm *loc;
 10     char buf[BUF_SIZE];
 11 
 12     if (setlocale(LC_ALL, "") == NULL)
 13         errExit("setlocale");
 14 
 15     t = time(NULL);
 16 
 17     printf("ctime() of time value is: %s", ctime(&t));
 18 
 19     loc = localtime(&t);
 20     if (loc == NULL)
 21         errExit("localtime");
 22 
 23     printf("asctime() of local time is: %s", asctime(loc));
 24 
 25     if (strftime(buf, BUF_SIZE, "%A, %d %B %Y, %H:%M:%S %Z", loc) == 0)
 26         fatal("strftime return 0");
 27 
 28     printf("strftime() of local time is: %s\n", buf);
 29 
 30     exit(EXIT_SUCCESS);
 31 }
 32 
输出:

wang@wang:~/test/tlpi-dist/lib$ TZ=":Patific/Auckland" ./show_time
ctime() of time value is: Thu Mar  9 09:32:47 2017
asctime() of local time is: Thu Mar  9 09:32:47 2017
strftime() of local time is: 星期四, 09 三月 2017, 09:32:47 Patific

(11)本地化工作

不怎么感冒。

(12)进程时间

The times() system call retrieves process time information, returning it in the structure pointed to by buf.

clock_t times(struct tms *buf);

struct tms {

    clock_t tms_utime;       /* user cpu time used by caller */

    clock_t tms_stime;       /* system cpu time by caller */

};

(13) clock函数

The clock() function provides a simpler interface for retrieving the process time. It returns a single value that measures the total CPU time used by the calling process.

clock_t clock(void);

(14)举例使用这些函数

  1 #include <sys/times.h>
  2 #include <time.h>
  3 #include "tlpi_hdr.h"
  4 
  5 /* Display 'msg' and process times */
  6 static void displayProcessTimes(const char *msg) {
  7     struct tms t;
  8     clock_t clockTime;
  9     static long clockTicks = 0;
 10 
 11     if (msg != NULL)
 12         printf("%s", msg);
 13     /* fetch clock ticks on first call */
 14     if (clockTicks == 0) {
 15         clockTicks = sysconf(_SC_CLK_TCK);
 16         if (clockTicks == -1)
 17             errExit("sysconf");
 18     }
 19     clockTime = clock();
 20     if (clockTime == -1)
 21         errExit("clock");
 22 
 23     printf("    clock() teturns: %ld clocks-per-sec (%.2f secs)\n",
 24         (long) clockTime, (double) clockTime / CLOCKS_PER_SEC);
 25 
 26     if (times(&t) == -1)
 27         errExit("times");
 28     printf("    times() yields: user CPU = %.2f; system CPU: %.2f\n",
 29         (double) t.tms_utime / clockTicks,
 30         (double) t.tms_stime / clockTicks);
 31 }
 32 
 33 int main(int argc, char *argv[]) {
 34     int numCalls, j;
 35     printf("CLOCKS_PER_SEC = %ld sysconf(_SC_CLK_TCK) = %ld\n\n",
 36         (long) CLOCKS_PER_SEC, sysconf(_SC_CLK_TCK));
 37 
 38     displayProcessTimes("At program start:\n");
 39     numCalls = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-calls") : 100000000;
 40     for (j = 0; j < numCalls; j++)
 41         (void) getppid();
 42     displayProcessTimes("After getppid() loop:\n");
 43     exit(EXIT_SUCCESS);
 44 }
输出:

wang@wang:~/test/tlpi-dist/lib$ ./process_time
CLOCKS_PER_SEC = 1000000 sysconf(_SC_CLK_TCK) = 100
At program start:
    clock() teturns: 1353 clocks-per-sec (0.00 secs)
    times() yields: user CPU = 0.00; system CPU: 0.00
After getppid() loop:
    clock() teturns: 4266929 clocks-per-sec (4.27 secs)
    times() yields: user CPU = 1.49; system CPU: 2.77

(15)总结

Real time corresponds to the everyday definition of time. When real time is measured from some standard point, we refer to it as calendar time, by contrast with elapsed time, which is measured from some point (usually the start) in the life of a process.

    Process time is the amount of CPU time used by a process, and is divided into user and system components.

    Various system calls enable us to get and set the system clock value (i.e., calendar time, as measured in seconds since the Epoch), and a range of library functions allow conversion between calendar time and other time formats, including broken-down time and human-readable character string. Describing such conversions took us into a discussion of locales and internationalization.

    Using and displaying times and dates is an important part of many applications, and we'll make frequent use of the functions described in this chapter in later parts of this book.

(16)习题



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值