10.时间编程

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));

}

 

运行的结果:

 

 

前面的操作总结:

posted @ 2016-02-14 08:32  cestlavie  阅读(775)  评论(0编辑  收藏  举报