windows下精确定时总结

2 篇文章 0 订阅
2 篇文章 0 订阅

windows下精确定时总结

本文对Windows平台下常用的计时函数进行总结,包括精度为秒、毫秒、微秒三种精度的5种方法。分为在标准C/C++下的二种time()clock(),标准C/C++所以使用的time()clock()不仅可以用在Windows系统,也可以用于Linux系统。在Windows系统下三种,使用Windows提供的API接口timeGetTime()GetTickCount()QueryPerformanceCounter()来完成。文章最后给出了5种计时方法示例代码。

标准C/C++的二个计时函数time()及clock()

time_t time(time_t *timer);

返回以格林尼治时间(GMT)为标准,从1970年1月1日00:00:00到现在的此时此刻所经过的秒数。time_t实际是个long长整型typedef long time_t;

头文件:#include

Windows系统API函数

主要是以下三个函数:
timeGetTime()、GetTickCount()及QueryPerformanceCounter()

DWORD timeGetTime(VOID);

返回系统时间,以毫秒为单位。系统时间是从系统启动到调用函数时所经过的毫秒数。注意,这个值是32位的,会在0到2^32之间循环,约49.71天。

头文件:#include

//Windows系统下time(),clock(),timeGetTime(),GetTickCount(),QueryPerformanceCounter()来计时 by MoreWindows
#include <stdio.h>
#include <windows.h>
#include <time.h> //time_t time()  clock_t clock()
#include <Mmsystem.h>             //timeGetTime()
#pragma comment(lib, "Winmm.lib")   //timeGetTime()

int main()
{
    //用time()来计时  秒
    time_t timeBegin, timeEnd;
    timeBegin = time(NULL);
    Sleep(1000);
    timeEnd = time(NULL);
    printf("%d\n", timeEnd - timeBegin);


    //用clock()来计时  毫秒
    clock_t  clockBegin, clockEnd;
    clockBegin = clock();
    Sleep(800);
    clockEnd = clock();
    printf("%d\n", clockEnd - clockBegin);


    //用timeGetTime()来计时  毫秒
    DWORD  dwBegin, dwEnd;
    dwBegin = timeGetTime();
    Sleep(800);
    dwEnd = timeGetTime();
    printf("%d\n", dwEnd - dwBegin);


    //用GetTickCount()来计时  毫秒
    DWORD  dwGTCBegin, dwGTCEnd;
    dwGTCBegin = GetTickCount();
    Sleep(800);
    dwGTCEnd = GetTickCount();
    printf("%d\n", dwGTCEnd - dwGTCBegin);


    //用QueryPerformanceCounter()来计时  微秒
    LARGE_INTEGER  large_interger;
    double dff;
    __int64  c1, c2;
    QueryPerformanceFrequency(&large_interger);
    dff = large_interger.QuadPart;
    QueryPerformanceCounter(&large_interger);
    c1 = large_interger.QuadPart;
    Sleep(800);
    QueryPerformanceCounter(&large_interger);
    c2 = large_interger.QuadPart;
    printf("本机高精度计时器频率%lf\n", dff);
    printf("第一次计时器值%I64d 第二次计时器值%I64d 计时器差%I64d\n", c1, c2, c2 - c1);
    printf("计时%lf毫秒\n", (c2 - c1) * 1000 / dff);

    printf("By MoreWindows\n");
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值