10.时间编程

1.时间的类型:

Coordinated Universal Time(UTC):世界标准时间,也就是大家所熟知的格林威治标准时间(Greenwich Mean Time,GMT)。

Calendar Time:日历时间,是用"从一个标准时间点(如:1970年1月1日0点)到此时经过的秒数"来表示的时间。

?

2.时间操作:

获取日历时间:man 2 time:

(主要:man 后面的数字表示的是章节:1(留空):命令 2:函数 3:系统调用。)

NAME

time - get time in seconds

?

SYNOPSIS

#include <time.h>

?

time_t time(time_t *t);

?

DESCRIPTION

time() returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured

in seconds.

?

If t is non-NULL, the return value is also stored in the memory pointed to by t.

?

RETURN VALUE

On success, the value of time in seconds since the Epoch is returned. On error,

((time_t) -1) is returned, and errno is set appropriately.

?

ERRORS

EFAULT t points outside your accessible address space.

?

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001. POSIX does not specify any error condi-

tions.

?

NOTES

POSIX.1 defines seconds since the Epoch as a value to be interpreted as the number

of seconds between a specified time and the Epoch, according to a formula for con-

version from UTC equivalent to conversion on the naive basis that leap seconds are

ignored and all years divisible by 4 are leap years. This value is not the same

as the actual number of seconds between the time and the Epoch, because of leap

seconds and because clocks are not required to be synchronized to a standard ref-

erence. The intention is that the interpretation of seconds since the Epoch val-

ues be consistent; see POSIX.1 Annex B 2.2.2 for further rationale.

?

SEE ALSO

date(1), gettimeofday(2), ctime(3), ftime(3), time(7)

?

COLOPHON

This page is part of release 3.22 of the Linux man-pages project. A description

of the project, and information about reporting bugs, can be found at

http://www.kernel.org/doc/man-pages/.

简单的解释:

使用time函数获取时间需要包含的头文件:time.h

原型:time_t time(time_t *t);

功能是返回日历时间。如果成功返回日历时间,失败则返回的是-1.

该函数有一个参数:不为空的情况下保存返回的时间。

Time.c:

#include <stdio.h>

#include <time.h>

void main(){

????time_t mytime;

????mytime = time(NULL);

????printf("time is %d \n!",mytime);

}

运行的结果:

上面的时间就是1970年到现在的秒数。

下面我们对上面的时间格式化成我们熟悉的形式。

?

格林威治时间:

在命令行执行:man 3 gmtime:

NAME

asctime, ctime, gmtime, localtime, mktime, asctime_r, ctime_r, gmtime_r, local-

time_r - transform date and time to broken-down time or ASCII

?

SYNOPSIS

#include <time.h>

?

char *asctime(const struct tm *tm);

char *asctime_r(const struct tm *tm, char *buf);

?

char *ctime(const time_t *timep);

char *ctime_r(const time_t *timep, char *buf);

?

struct tm *gmtime(const time_t *timep);

struct tm *gmtime_r(const time_t *timep, struct tm *result);

?

struct tm *localtime(const time_t *timep);

struct tm *localtime_r(const time_t *timep, struct tm *result);

?

time_t mktime(struct tm *tm);

?

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

?

asctime_r(), ctime_r(), gmtime_r(), localtime_r():

_POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE ||

_POSIX_SOURCE

DESCRIPTION

The ctime(), gmtime() and localtime() functions all take an argument of data type

time_t which represents calendar time. When interpreted as an absolute time

value, it represents the number of seconds elapsed since 00:00:00 on January 1,

1970, Coordinated Universal Time (UTC).

?

The asctime() and mktime() functions both take an argument representing broken-

down time which is a representation separated into year, month, day, etc.

?

Broken-down time is stored in the structure tm which is defined in <time.h> as

follows:

?

struct tm {

int tm_sec; /* seconds */

int tm_min; /* minutes */

int tm_hour; /* hours */

int tm_mday; /* day of the month */

int tm_mon; /* month */

int tm_year; /* year */

int tm_wday; /* day of the week */

int tm_yday; /* day in the year */

int tm_isdst; /* daylight saving time */

};

?

The members of the tm structure are:

?

tm_sec The number of seconds after the minute, normally in the range 0 to 59,

but can be up to 60 to allow for leap seconds.

?

tm_min The number of minutes after the hour, in the range 0 to 59.

?

tm_hour The number of hours past midnight, in the range 0 to 23.

?

tm_mday The day of the month, in the range 1 to 31.

?

tm_mon The number of months since January, in the range 0 to 11.

?

tm_year The number of years since 1900.

?

tm_wday The number of days since Sunday, in the range 0 to 6.

?

tm_yday The number of days since January 1, in the range 0 to 365.

?

tm_isdst A flag that indicates whether daylight saving time is in effect at the

time described. The value is positive if daylight saving time is in

effect, zero if it is not, and negative if the information is not avail-

able.

?

The call ctime(t) is equivalent to asctime(localtime(t)). It converts the calen-

dar time t into a null-terminated string of the form

?

"Wed Jun 30 21:49:08 1993\n"

?

The abbreviations for the days of the week are "Sun", "Mon", "Tue", "Wed", "Thu",

"Fri", and "Sat". The abbreviations for the months are "Jan", "Feb", "Mar",

"Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", and "Dec". The return

value points to a statically allocated string which might be overwritten by subse-

quent calls to any of the date and time functions. The function also sets the

external variables tzname, timezone, and daylight (see tzset(3)) with information

about the current timezone. The reentrant version ctime_r() does the same, but

stores the string in a user-supplied buffer which should have room for at least 26

bytes. It need not set tzname, timezone, and daylight.

?

The gmtime() function converts the calendar time timep to broken-down time repre-

sentation, expressed in Coordinated Universal Time (UTC). It may return NULL when

the year does not fit into an integer. The return value points to a statically

allocated struct which might be overwritten by subsequent calls to any of the date

and time functions. The gmtime_r() function does the same, but stores the data in

a user-supplied struct.

?

The localtime() function converts the calendar time timep to broken-time represen-

tation, expressed relative to the user‘s specified timezone. The function acts as

if it called tzset(3) and sets the external variables tzname with information

about the current timezone, timezone with the difference between Coordinated Uni-

versal Time (UTC) and local standard time in seconds, and daylight to a non-zero

value if daylight savings time rules apply during some part of the year. The

return value points to a statically allocated struct which might be overwritten by

subsequent calls to any of the date and time functions. The localtime_r() func-

tion does the same, but stores the data in a user-supplied struct. It need not

set tzname, timezone, and daylight.

The asctime() function converts the broken-down time value tm into a null-termi-

nated string with the same format as ctime(). The return value points to a stati-

cally allocated string which might be overwritten by subsequent calls to any of

the date and time functions. The asctime_r() function does the same, but stores

the string in a user-supplied buffer which should have room for at least 26 bytes.

?

The mktime() function converts a broken-down time structure, expressed as local

time, to calendar time representation. The function ignores the values supplied

by the caller in the tm_wday and tm_yday fields. The value specified in the

tm_isdst field informs mktime() whether or not daylight saving time (DST) is in

effect for the time supplied in the tm structure: a positive value means DST is in

effect; zero means that DST is not in effect; and a negative value means that

mktime() should (use timezone information and system databases to) attempt to

determine whether DST is in effect at the specified time.

?

The mktime() function modifies the fields of the tm structure as follows: tm_wday

and tm_yday are set to values determined from the contents of the other fields; if

structure members are outside their valid interval, they will be normalized (so

that, for example, 40 October is changed into 9 November); tm_isdst is set

(regardless of its initial value) to a positive value or to 0, respectively, to

indicate whether DST is or is not in effect at the specified time. Calling

mktime() also sets the external variable tzname with information about the current

timezone.

?

If the specified broken-down time cannot be represented as calendar time (seconds

since the Epoch), mktime() returns a value of (time_t) -1 and does not alter the

members of the broken-down time structure.

RETURN VALUE

Each of these functions returns the value described, or NULL (-1 in case of

mktime()) in case an error was detected.

?

CONFORMING TO

POSIX.1-2001. C89 and C99 specify asctime(), ctime(), gmtime(), localtime(), and

mktime(). POSIX.1-2008 marks asctime(), asctime_r(), ctime(), and ctime_r() as

obsolete, recommending the use of strftime(3) instead.

?

NOTES

The four functions asctime(), ctime(), gmtime() and localtime() return a pointer

to static data and hence are not thread-safe. Thread-safe versions asctime_r(),

ctime_r(), gmtime_r() and localtime_r() are specified by SUSv2, and available

since libc 5.2.5.

?

POSIX.1-2001 says: "The asctime(), ctime(), gmtime(), and localtime() functions

shall return values in one of two static objects: a broken-down time structure and

an array of type char. Execution of any of the functions may overwrite the infor-

mation returned in either of these objects by any of the other functions." This

can occur in the glibc implementation.

?

In many implementations, including glibc, a 0 in tm_mday is interpreted as meaning

the last day of the preceding month.

?

The glibc version of struct tm has additional fields

long tm_gmtoff; /* Seconds east of UTC */

const char *tm_zone; /* Timezone abbreviation */

?

defined when _BSD_SOURCE was set before including <time.h>. This is a BSD exten-

sion, present in 4.3BSD-Reno.

?

According to POSIX.1-2004, localtime() is required to behave as though tzset() was

called, while localtime_r() does not have this requirement. For portable code

tzset() should be called before localtime_r().

?

SEE ALSO

date(1), gettimeofday(2), time(2), utime(2), clock(3), difftime(3), strftime(3),

strptime(3), timegm(3), tzset(3), time(7)

?

COLOPHON

This page is part of release 3.22 of the Linux man-pages project. A description

of the project, and information about reporting bugs, can be found at

http://www.kernel.org/doc/man-pages/.

格林时间的函数:

struct tm *gmtime(const time_t *timep);

该函数的功能是将参数timep所指定的日历时间转化为标准的时间,我们习惯的时间格式。

使用该函数需要包含的头文件:time.h

该函数的返回值是:成功的情况下返回标准时间,显示的结构:struct tm格式。

Gmtime.c:

#include <stdio.h>

#include <time.h>

void main(){

????time_t mytime;

????struct tm *mytm;

????//get time

????mytime = time(NULL);

????//format time

????mytm = gmtime(&mytime);

????printf("hour: %d , minue:%d \n!",mytm->tm_hour,mytm->tm_min);

}

/*struct tm {

int tm_sec; /* seconds */

int tm_min; /* minutes */

int tm_hour; /* hours */

int tm_mday; /* day of the month */

int tm_mon; /* month */

int tm_year; /* year */

int tm_wday; /* day of the week */

int tm_yday; /* day in the year */

int tm_isdst; /* daylight saving time */

};*/

程序运行的结果:

?

?

获取当地时间:

函数的名字:

struct tm *localtime(const time_t *timep);

该函数的功能是将参数的时间转化为本地时间。需要的头文件:time.h。

他的返回值是:成功则以struct tm形式返回本地时间。

参数是待转化的日历时间。

Localtime.c:

#include <stdio.h>

#include <time.h>

void main(){

????time_t mytime;

????struct tm *mytm;

????//get time

????mytime = time(NULL);

????//format time

????mytm = localtime(&mytime);

????printf("hour: %d , minue:%d \n!",mytm->tm_hour,mytm->tm_min);

}

?

运行的结果:

?

?

?

字符串形式的时间:

函数的原型:

char *asctime(const struct tm *tm);

该函数的返回值是字符串,参数是tm结构。函数的功能是以字符串的形式。需要的头文件是time.h.

Chartime.c:

#include <stdio.h>

#include <time.h>

void main(){

????time_t mytime;

????struct tm *mytm;

????char *mychartime;

?

????//get time

????mytime = time(NULL);

????//format time

????mytm = localtime(&mytime);

????printf("hour: %d , minue:%d \n!",mytm->tm_hour,mytm->tm_min);

?

????mychartime = asctime(mytm);

????printf("time is %s\n",mychartime);

}

运行结果:

?

?

获取高精度时间:

执行命令:man 2 gettimeofday:

NAME

gettimeofday, settimeofday - get / set time

?

SYNOPSIS

#include <sys/time.h>

?

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

?

int settimeofday(const struct timeval *tv, const struct timezone *tz);

?

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

?

settimeofday(): _BSD_SOURCE

?

DESCRIPTION

The functions gettimeofday() and settimeofday() can get and set the time as well

as a timezone. The tv argument is a struct timeval (as specified in

<sys/time.h>):

?

struct timeval {

time_t tv_sec; /* seconds */

suseconds_t tv_usec; /* microseconds */

};

?

and gives the number of seconds and microseconds since the Epoch (see time(2)).

The tz argument is a struct timezone:

struct timezone {

int tz_minuteswest; /* minutes west of Greenwich */

int tz_dsttime; /* type of DST correction */

};

?

If either tv or tz is NULL, the corresponding structure is not set or returned.

?

The use of the timezone structure is obsolete; the tz argument should normally be

specified as NULL. The tz_dsttime field has never been used under Linux; it has

not been and will not be supported by libc or glibc. Each and every occurrence of

this field in the kernel source (other than the declaration) is a bug. Thus, the

following is purely of historic interest.

?

The field tz_dsttime contains a symbolic constant (values are given below) that

indicates in which part of the year Daylight Saving Time is in force. (Note: its

value is constant throughout the year: it does not indicate that DST is in force,

it just selects an algorithm.) The daylight saving time algorithms defined are as

follows :

?

DST_NONE /* not on dst */

DST_USA /* USA style dst */

DST_AUST /* Australian style dst */

DST_WET /* Western European dst */

DST_MET /* Middle European dst */

DST_EET /* Eastern European dst */

DST_CAN /* Canada */

DST_GB /* Great Britain and Eire */

DST_RUM /* Rumania */

DST_TUR /* Turkey */

DST_AUSTALT /* Australian style with shift in 1986 */

?

Of course it turned out that the period in which Daylight Saving Time is in force

cannot be given by a simple algorithm, one per country; indeed, this period is

determined by unpredictable political decisions. So this method of representing

timezones has been abandoned. Under Linux, in a call to settimeofday() the

tz_dsttime field should be zero.

?

Under Linux there are some peculiar "warp clock" semantics associated with the

settimeofday() system call if on the very first call (after booting) that has a

non-NULL tz argument, the tv argument is NULL and the tz_minuteswest field is non-

zero. In such a case it is assumed that the CMOS clock is on local time, and that

it has to be incremented by this amount to get UTC system time. No doubt it is a

bad idea to use this feature.

?

Macros for operating on timeval structures are described in timeradd(3).

?

RETURN VALUE

gettimeofday() and settimeofday() return 0 for success, or -1 for failure (in

which case errno is set appropriately).

?

ERRORS

EFAULT One of tv or tz pointed outside the accessible address space.

?

EINVAL Timezone (or something else) is invalid.

EPERM The calling process has insufficient privilege to call settimeofday();

under Linux the CAP_SYS_TIME capability is required.

?

CONFORMING TO

SVr4, 4.3BSD. POSIX.1-2001 describes gettimeofday() but not settimeofday().

POSIX.1-2008 marks gettimeofday() as obsolete, recomending the use of clock_get-

time(2) instead.

?

NOTES

Traditionally, the fields of struct timeval were of type long.

?

SEE ALSO

date(1), adjtimex(2), time(2), ctime(3), ftime(3), capabilities(7), time(7)

?

COLOPHON

This page is part of release 3.22 of the Linux man-pages project. A description

of the project, and information about reporting bugs, can be found at

http://www.kernel.org/doc/man-pages/.

?

?

函数的原型:

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

需要包含的头文件:

#include <sys/time.h>

该函数的返回值是int类型,第一个参数struct timeval *tv,该参数保存的是从1970年到现在的时间。第二个参数是struct timezone *tz通常为NULL。

该函数的功能:获取高精度的时间。

struct timeval {

time_t tv_sec; /* seconds */

suseconds_t tv_usec; /* microseconds */

};

struct timezone {

int tz_minuteswest; /* minutes west of Greenwich */

int tz_dsttime; /* type of DST correction */

};

成功返回0,失败返回-1.

编程:gettimeofday.c

#include <sys/time.h>

#include <stdio.h>

void main(){

????struct timeval tv;

????gettimeofday(&tv, NULL);

????printf("sec is %d , usec is %d \n",tv.tv_sec,tv.tv_usec);

}

?

运行的结果:

在上面的运行结果中sec是现在的秒数,usec是现在的微秒数。

用上面的微秒我们可以实现一个计算一个程序运行的时间:

?

?

?

Count.c:

#include <sys/time.h>

#include <stdio.h>

void count(){

????int i,j;

????int temp;

????for(i=0;i<9999;i++){

????????for(j=0;j<9999;j++){

????????????temp=i+j;

????????}

????}

}

?

void main(){

????struct timeval tv1;

????struct timeval tv2;

?

????gettimeofday(&tv1, NULL);

????count();

????gettimeofday(&tv2, NULL);

?

????printf("sec is %d , usec is %d \n",(tv2.tv_sec-tv1.tv_sec),(tv2.tv_usec-tv1.tv_usec));

}

?

运行的结果:

?

?

前面的操作总结:

时间: 2024-10-12 19:17:42

10.时间编程的相关文章

10年后编程还有意义吗?

这个是 Quora 上提出的一个问题.随着 AI 在近年来成为热门话题,并且在 AlphaGo 自学围棋击败了人类近 10 年最好的围棋选手之后,有人开始提出这个问题.具体来说这个问题有三层意思:到 2025 年程序员还有没有用,到那个时候所谓的 “程序员” 是指什么?代码本身还有没有用,到那时候代码会变成什么样子?机器智能会不会取代(目前意义的)代码或程序员两者的其中一个或者全部?大家基本上倾向于认为,到 2025 年时编程仍然有意义,但有人说 2025 年以后情况可能就不是这样了. 而那些认

浅析 Linux 中的时间编程和实现原理一—— Linux 应用层的时间编程【转】

本文转载自:http://www.cnblogs.com/qingchen1984/p/7007631.html 本篇文章主要介绍了"浅析 Linux 中的时间编程和实现原理一—— Linux 应用层的时间编程",主要涉及到浅析 Linux 中的时间编程和实现原理一—— Linux 应用层的时间编程方面的内容,对于浅析 Linux 中的时间编程和实现原理一—— Linux 应用层的时间编程感兴趣的同学可以参考一下. 简介: 本文试图完整地描述 Linux 系统中 C 语言编程中的时间问

每个程序员都该知道的10大编程格言

每个程序员都该知道的10大编程格言 编程格言1:无风不起浪 (There is no smoke without fire) 编程格言2:预防为主,治疗为辅(An ounce of prevention is worth a pound of cure:) 编程格言3:不要把鸡蛋都放在一个篮子(Don't put all your eggs in one basket) 编程格言4:种瓜得瓜,种豆得豆(As you sow,so shoul you reap) 编程格言5:欲速则不达(Great

Linux 下的时间编程总结

在嵌入式编程中中,经常需要输出系统的当前时间.计算程序的执行时间.使用计时器等.最近也做了不少关于时间的操作,今天就认真总结一下,部分内容是在网上看到的.自己经过验证总结出来. 1.时间的类型 1.格林威治标准时间 coordinated universal time(UTC)是世界标准时间,即常说的格林威治标准时间(greenwich mean time,GMT). 2.日历时间 日历时间(calendar time)是用"一个标准时间点(如1970年1月1日0点)到此时经过的秒数"

linux应用开发-时间编程

linux应用开发-时间编程 一 时间类型 世界标准时间:格林威治时间 日历时间:从1970-1-1起的秒数 二 时间函数 1 获取日历时间 函数名 time 函数原形 time_t time(time_t *t) 函数功能 从1970年1月1日的时间,单位为秒 所属头文件 #include<time.h> 返回值 成功返回时间的秒速 失败返回-1 参数说明 保存返回值 2 获取格林威治时间 函数名 gmtime 函数原形 struct tm *gmtime(const time_t *tim

漂亮的10大编程字体

10. Courier 基本上所有的系统都自带了此种字体,有时候它又以Courier New的名字出现.不幸的是很多终端和编辑器都默认使用此种字体,虽然这不会影响使用,但这会影响心情,它太枯燥了.以前看到这样一句评论:久不见牡丹会以仙人掌为美.这句评论形Courier字体非常合适.所以如果你还有其他选择的话,请勿使用此字体.更不幸的事情是最后你还是会继续使用它,那3秒只能强烈建议你调整一下字体大小并消除锯齿. 9. Andale Mono 稍微比Courier好一点的字体,有些时候它也被用作默认

时间编程

使用Linux时间编程相关函数,编写程序,通过实现与函数asctime相同功能的函数获取本地时间,以格式字符串方式显示 概念:日历时间,通过time_t数据类型来表示,从一个时间点(通常是1970年1月1日0时0分0秒)到此时的秒数. 格林威治时间:由英国皇家格林尼治天文台提供的标准时间. 本地时间:根据格林威治时间和本地时区计算出的时间. 1.获取当前的系统时间--time 头文件:#include<time.h> 函数原型:time_t time(time_t *timer) 参数说明:t

(一)Python入门-2编程基本概念:10时间表示-unix时间点-毫秒和微妙-time模块

一:时间表示 计算机中时间的表示是从“1970 年 1月 1日 00:00:00”开始,以毫秒(1/1000 秒) 进行计算.我们也把1970 年这个时刻成为“unix 时间点”. 这样,我们就把时间全部用数字来表示了.时间本质上就是数字 python中可以通过 time.time() 获得当前时刻,返回的值是以秒为单位,带微秒 (1/1000 毫秒)精度的浮点值.例如:1530167364.8566. [操作] 1 >>> import time 2 >>> b =

10年编程无师自通

原文:Teach Yourself Programming in Ten Years 作者:Peter Norvig 翻译:郭晓刚([email protected]) 最后修订日期:2004-3-19 2005-01-12增加了新的译本链接. 本中文译本得到了Peter Norvig的许可. 为什么每个人都急不可耐? 走进任何一家书店,你会看见<Teach Yourself Java in 7 Days>(7天Java无师自通)的旁边是一长排看不到尽头的类似书籍,它们要教会你Visual B