您的位置:首页 > 编程语言 > C语言/C++

C/C++-技巧-获取时间

2017-01-31 17:12 323 查看

一、c/c++标准中的时间

头文件<ctime>

1、时间的表示

typedef __time64_t time_t; /* time value */
使用一个长整型表示时间,单位为秒。

struct timespec
{
time_t tv_sec; // Seconds - >= 0
long tv_nsec; // Nanoseconds - [0, 999999999]
};使用两个变量来表示时间,tv_sec表示格林威治标准时间(GMT)1970-1-1 0:0:0开始到现在的秒数,ty_nsec则表示秒数后面的精度,单位为纳秒。

struct tm
{
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};用一个结构体表示具体的日期、时间。

2、接口

static __inline time_t __CRTDECL time(time_t * _Time)该函数返回格林威治标准时间(GMT)1970-1-1 0:0:0开始到现在的秒数,属于机器时间,即无论处于哪一个时区,同一时刻该函数所获取到的机器都是相同的,所以该时间是相对时间。

有了机器时间后,然后就需要将其转化为本地系统时间或标准时间,可以使用下面一系列函数实现:

static __inline struct tm * __CRTDECL gmtime(const time_t * _Time)该函数把机器时间转换为格林威治时间(GMT)。

static __inline struct tm * __CRTDECL localtime(const time_t * _Time)该函数把机器时间转换为经过时区转化后的本地时间。

但是通过time()等相关接口获取的时间精度仅仅在秒级,如果要获取更高精度的时间,需要借助timespec结构体来获取微妙级精度。

注意:struct timespec在VC12下的time.h没有定义,需要用VC14

二、linux下的时间

头文件<sys/time.h>

struct timeval
{
time_t tv_sec; /* Seconds. */
suseconds_t tv_usec; /* Microseconds. */
};

使用两个变量来表示时间,tv_sec表示格林威治标准时间(GMT)1970-1-1 0:0:0开始到现在的秒数,ty_usec则表示秒数后面的精度,单位为微秒。

一般使用下面的接口获取系统时间:

int gettimeofday(struct timeval *tv, struct timezone *tz);
使用timeval精确到毫秒。

int clock_gettime(clockid_t clk_id, struct timespec *tp);
使用timespec精确到微妙。

三、windows下的时间

WINBASEAPI
VOID
WINAPI
GetLocalTime(
_Out_ LPSYSTEMTIME lpSystemTime
);获取日期时间,精确到毫秒级。

WINBASEAPI
BOOL
WINAPI
QueryPerformanceFrequency(
_Out_ LARGE_INTEGER * lpFrequency
);

WINBASEAPI
BOOL
WINAPI
QueryPerformanceCounter(
_Out_ LARGE_INTEGER * lpPerformanceCount
);

首先获取windows内部微秒级高精度定时器的频率(单位为1/s),然后再获取定时器当前的时钟次数,次数/频率=时间。

参考:
http://www.cnblogs.com/book-gary/p/3716790.html http://blog.csdn.net/wangluojisuan/article/details/7045592/  http://blog.csdn.net/jack237/article/details/7344694 http://blog.csdn.net/huang3838438/article/details/7399401
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 系统时间