C++获取当前系统时间

首先,包含如下头文件:

1
2
#include "sys/time.h"
#include <unistd.h>

实现函数,分不同平台:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double Common::getTime() {
#ifdef _WIN32
FILETIME ft;
double t;
GetSystemTimeAsFileTime(&ft);
/* Windows file time (time since January 1, 1601 (UTC)) */
t = ft.dwLowDateTime/1.0e7 + ft.dwHighDateTime*(4294967296.0/1.0e7);
/* convert to Unix Epoch time (time since January 1, 1970 (UTC)) */
return (t - 11644473600.0);
#else
struct timeval v;
gettimeofday(&v, (struct timezone *) NULL);
/* Unix Epoch time (time since January 1, 1970 (UTC)) */
return v.tv_sec + v.tv_usec/1.0e6;
#endif
}