计算时差 [英] Calculating time difference

查看:122
本文介绍了计算时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿.我想计算代码的运行时间.
假设我有2个日期,我想以毫秒或微秒为单位计算差异.

最好的方法是什么?

Hey. I want to calculate the running time of the code.
Lets say i have 2 dates i want to calculate the difference in milliseconds or microseconds.

What is the best way to do it?

推荐答案

您没有说您使用的是哪个操作系统.对于Windows,性能计数器是最佳选择.

这是一个使用性能计数器的小类,可用于测量代码执行时间:

You did not say which operating system you are using. With Windows, the performance counter is the best choice.

Here is a small class using the performance counter that can be used to measure code execution time:

// MyTimer.h
class CMyTimer
{
public:
    CMyTimer(bool bStart = false);
    
    bool		Start();
    double		GetElapsedTime() const;
    inline DWORD 	GetElapsedTimeMS() const
    { return static_cast<DWORD>(1E3 * GetElapsedTime()); }
    inline void		Stop() { m_qwStartTime.QuadPart = 0LL; }
    inline bool		IsStarted() const { return m_qwStartTime.QuadPart != 0LL; }
    inline LONGLONG	GetStartTime() const { return m_qwStartTime.QuadPart; }
    inline LONGLONG	GetFrequency() const { return s_qwPerfFreq.QuadPart; }
protected:
    LARGE_INTEGER	m_qwStartTime;
private:
    static LARGE_INTEGER s_qwPerfFreq;
};


// MyTimer.cpp
#include "MyTimer.h"

/*static*/ LARGE_INTEGER CMyTimer::s_qwPerfFreq = { 0 };

CMyTimer::CMyTimer(bool bStart /*= false*/)
{
    m_qwStartTime.QuadPart = 0LL;
    if (bStart)
        Start();
}

bool CMyTimer::Start(void)
{
    // Get performance counter frequency once with first call.
    if (0LL == s_qwPerfFreq.QuadPart)
    	::QueryPerformanceFrequency(&s_qwPerfFreq);
    return (0LL != s_qwPerfFreq.QuadPart && 
        ::QueryPerformanceCounter(&m_qwStartTime));
}

// Get elapsed time in seconds.
double CMyTimer::GetElapsedTime() const
{
    LARGE_INTEGER qwEndTime;
    return (IsStarted() && ::QueryPerformanceCounter(&qwEndTime)) ?
        static_cast<double>(qwEndTime.QuadPart - m_qwStartTime.QuadPart) / 
        static_cast<double>(s_qwPerfFreq.QuadPart) :
        0.0;
}


可以这样使用:


This can be used this way:

CMyTimer Timer(true);
// execute some time consuming code
_tprintf(_T("Code excution took %.5f seconds\n"), Timer.GetElapsedTime());


这篇关于计算时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆