栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C/C++计时方法概括

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C/C++计时方法概括

法一:clock()

  1. 说明描述
    C 库函数 clock_t clock(void) 返回程序执行起(一般为程序的开头),处理器时钟所使用的时间。为了获取 CPU 所使用的秒数,您需要除以 CLOCKS_PER_SEC。
    在 32 位系统中,CLOCKS_PER_SEC 等于 1000000,该函数大约每 72 分钟会返回相同的值。

  2. 头文件及声明
    C 标准库 - — 头文件
    clock_t clock(void) — 函数声明

  3. 返回值
    该函数返回自程序启动起,处理器时钟所使用的时间。如果失败,则返回 -1 值。

  4. 使用方法
    clock_t start_t, end_t;
    start_t = clock();
    // Todo …
    end_t = clock();
    total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;

  5. 注意事项
    在不同平台下的返回值不同,使用时,需要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()

  1. 描述说明
    GetSystemTimePreciseAsFileTime函数以 尽可能高的精度 (<1us) 检索当前系统日期和时间。检索到的信息采用协调世界时 (UTC) 格式。

  2. 头文件及声明
    sysinfoapi.h — 头文件

void GetSystemTimePreciseAsFileTime( [out] LPFILETIME lpSystemTimeAsFileTime ); — 声明

  1. 参数
    [out] lpSystemTimeAsFileTime

Type: LPFILETIME — 一个结构体

A pointer to a FILETIME structure that contains the current system date and time in UTC format.

  1. 返回值
    none

  2. 使用方法
    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;

  3. 注意事项
    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.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948423.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号