C++ 高精度计时
程序员文章站
2024-03-20 22:28:22
...
#ifndef STOPWATCH_H
#define STOPWATCH_H
#include <Windows.h>
// ************************ 文件说明 **************************
//
// 该类通过使用 Windows API 获取 CPU 的时钟频率,来实现高精度计时,
// 可计时精度为微秒,因个人习惯,在 C# 中,使用 Stopwatch 进行计时,
// 所以,此处亦将该类命名为 Stopwatch
//
// ************************************************************
struct Elapsed;
class Stopwatch
{
public:
Stopwatch();
~Stopwatch();
public:
void start();
void stop();
void restart();
Elapsed elapsed() const;
private:
LARGE_INTEGER m_freq; // 该变量用于存储 cpu 时钟频率
LARGE_INTEGER m_start; // 该变量用于存储计时开始时的时钟频率
LARGE_INTEGER m_end; // 该变量用于存储计时结束时的时钟频率
Elapsed *m_elapsed;
};
struct Elapsed
{
double getMicroSeconds() const; // 获取微秒
double getMilliSeconds() const; // 获取毫秒
double getSeconds() const; // 获取秒
double m_microSeconds = 0; // 微秒
double m_milliSecodes = 0; // 毫秒
double m_seconds = 0; // 秒
};
#include "Stopwatch.h"
Stopwatch::Stopwatch()
{
m_elapsed = new Elapsed();
QueryPerformanceFrequency(&m_freq);
}
Stopwatch::~Stopwatch()
{
// 释放内存
if (m_elapsed != nullptr)
{
delete m_elapsed;
m_elapsed = nullptr;
}
}
void Stopwatch::start()
{
QueryPerformanceCounter(&m_start);
}
void Stopwatch::stop()
{
QueryPerformanceCounter(&m_end);
m_elapsed->m_microSeconds += 1000000.0 * (static_cast<double>(m_end.QuadPart)
- static_cast<double>(m_start.QuadPart)) / static_cast<double>(m_freq.QuadPart);
}
void Stopwatch::restart()
{
m_elapsed->m_microSeconds = 0;
start();
}
Elapsed Stopwatch::elapsed() const
{
return *m_elapsed;
}
double Elapsed::getMicroSeconds() const
{
return m_microSeconds;
}
double Elapsed::getMilliSeconds() const
{
return m_microSeconds / 1000.0;
}
double Elapsed::getSeconds() const
{
return m_microSeconds / 1000000.0;
}