Windows下获取us级代码执行时间

如题,对某段代码获取其运行消耗的时间(微秒级别)。

一、涉及到2个系统API函数

  • QueryPerformanceFrequency函数,其原型如下:
BOOL QueryPerformanceFrequency(
  LARGE_INTEGER *lpFrequency
);

微软帮助文档:

https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancefrequency

  • QueryPerformanceCounter函数,其原型如下:
BOOL QueryPerformanceCounter(
  LARGE_INTEGER *lpPerformanceCount
);

微软帮助文档:

https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter

嗯,没什么好讲的,自己看帮助,或者直接看代码吧。

二、封装计时器CTimer类

CTimer.h:

#ifndef CTIMER_H
#define CTIMER_H

#include <Windows.h>

class CTimer
{
public:
    __forceinline CTimer()
    {
        QueryPerformanceFrequency(&m_Frequency);
        QueryPerformanceCounter(&m_StartCount);
    }

    __forceinline void reset()
    {
        QueryPerformanceCounter(&m_StartCount);
    }

    __forceinline double end()
    {
        QueryPerformanceCounter(&nCurCount);
        double elapsedTime = static_cast<double>(nCurCount.QuadPart - m_StartCount.QuadPart) /
                m_Frequency.QuadPart * 1000 * 1000 ;
        return elapsedTime;
    }

private:
    LARGE_INTEGER m_Frequency;
    LARGE_INTEGER m_StartCount;
    LARGE_INTEGER nCurCount;
};

#endif // CTIMER_H

三、测试代码

main.cpp:

#include <QCoreApplication>
#include <QDebug>
#include "CTimer.h"

void testLogic(int repeat)
{
    int sum = 0;
    for (int i = 0; i < repeat; i++)
    {
        sum += i;
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    double elapsed;
    CTimer timer;
    timer.reset();  // 开始计时

    testLogic(1000); // 运行逻辑

    elapsed = timer.end();  // 结束计时
    qDebug() << "elapsed time:" << elapsed << "us";

    ///
    timer.reset();  // 开始计时

    testLogic(10000); // 运行逻辑

    elapsed = timer.end();  // 结束计时
    qDebug() << "elapsed time:" << elapsed << "us";

    return a.exec();
}

运行效果,如下:

在这里插入图片描述

测试环境:Win10系统,Qt5.12+MSVC编译



若对你有帮助,欢迎点赞、收藏、评论,你的支持就是我的最大动力!!!

同时,阿超为大家准备了丰富的学习资料,欢迎关注公众号“超哥学编程”,即可领取。

本文涉及工程代码,公众号回复:13WindowsCountTime,即可下载。

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值