法一:clock()
-
说明描述
C 库函数 clock_t clock(void) 返回程序执行起(一般为程序的开头),处理器时钟所使用的时间。为了获取 CPU 所使用的秒数,您需要除以 CLOCKS_PER_SEC。
在 32 位系统中,CLOCKS_PER_SEC 等于 1000000,该函数大约每 72 分钟会返回相同的值。 -
头文件及声明
C 标准库 -— 头文件
clock_t clock(void) — 函数声明 -
返回值
该函数返回自程序启动起,处理器时钟所使用的时间。如果失败,则返回 -1 值。 -
使用方法
clock_t start_t, end_t;
start_t = clock();
// Todo …
end_t = clock();
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC; -
注意事项
在不同平台下的返回值不同,使用时,需要clock() / CLOCKS_PER_SEC is a time in seconds,CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,也就是硬件滴答数。
先不管什么叫硬件滴答数,你需要知道clock()是基于时钟计时单元(clock tick)的这个东西来计数的。一个clock tick不是CPU的一个时钟周期,而是C/C++的一个基本计时单位,因此只与编译器有关。在TC2.0中硬件每18.2个滴答是一秒,在VC中硬件每1000个滴答是一秒,在标准POSIX中定义为1000000个滴答为一秒。
注意:精度问题,经搜索发现,标准POSIX平台的clock()只能精确到10ms.
法二:GetSystemTimePreciseAsfileTime()
-
描述说明
GetSystemTimePreciseAsFileTime函数以 尽可能高的精度 (<1us) 检索当前系统日期和时间。检索到的信息采用协调世界时 (UTC) 格式。 -
头文件及声明
sysinfoapi.h — 头文件
void GetSystemTimePreciseAsFileTime( [out] LPFILETIME lpSystemTimeAsFileTime ); — 声明
- 参数
[out] lpSystemTimeAsFileTime
Type: LPFILETIME — 一个结构体
A pointer to a FILETIME structure that contains the current system date and time in UTC format.
-
返回值
none -
使用方法
FILETIME fileTime;
long long now_long;
GetSystemTimeAsFileTime(&fileTime);
now_long = (long long(fileTime.dwHighDateTime) << 32) + fileTime.dwLowDateTime;
std::cout << "micro time from 1601.1.1:00:00:00 is: " << (now_long / 10) << std::endl; -
注意事项
Note This function is best suited for high-resolution time-of-day measurements, or time stamps that are synchronized to UTC. For high-resolution interval measurements, use QueryPerformanceCounter or KeQueryPerformanceCounter. For more info about acquiring high-resolution time stamps, see Acquiring high-resolution time stamps.



