0

I am trying to create a timer where it begins with a certain value and ends with another value like.

int pktctr = (unsigned char)unpkt[0];

if(pktctr == 2)
{
    cout << "timer-begin" << endl;
    //start timer here

}

if(pktctr == 255)
{
    cout << "timer-end" << endl;
    //stop timer here
    //timer display total time then reset.

}

cout << "displays total time it took from 1 to 255 here" << endl;

Any idea on how to achieve this?

void WINAPI MyUCPackets(char* unpkt, int packetlen, int iR, int arg)
{
int pktctr = (unsigned char)unpkt[0];

if(pktctr == 2)
{
    cout << "timer-begin" << endl;

}

if(pktctr == 255)
{
    cout << "timer-end" << endl;

}

return MyUC2Packets(unpkt,packetlen,iR,arg);
}

Everytime this function is called unpkt starts from 2 then reaches max of 255 then goes back to 1. And I want to compute how long it took for every revolution?

This will happen alot of times. But I just wanted to check how many seconds it took for this to happen because it won't be the same everytime.

Note: This is done with MSDetours 3.0...

4

3 回答 3

0

如果您想使用 Windows-API,请使用GetSystemTime(). 提供一个 struct SYSTEMTIME,正确初始化它并将其传递给GetSystemTime()

#include <Windows.h>

 ...
 SYSTEMTIME sysTime;
 GetFileTime(&sysTime);
 // use sysTime and create differences

这里GetSystemTime()那里也有链接SYSTEMTIME

于 2013-03-21T20:37:46.047 回答
0

我假设您使用的是 Windows(来自WINAPI代码中的),在这种情况下您可以使用GetTickCount

/* or you could have this elsewhere, e.g. as a class member or
 * in global scope (yuck!) As it stands, this isn't thread safe!
 */
static DWORD dwStartTicks = 0;

int pktctr = (unsigned char)unpkt[0];

if(pktctr == 2)
{
    cout << "timer-begin" << endl;
    dwStartTicks = GetTickCount();
}

if(pktctr == 255)
{
    cout << "timer-end" << endl;

    DWORD dwDuration = GetTickCount() - dwStartTicks;

    /* use dwDuration - it's in milliseconds, so divide by 1000 to get
     * seconds if you so desire.
     */
}

需要注意的事情:溢出GetTickCount是可能的(它大约每 47 天重置为 0,因此如果您在接近翻转时间时启动计时器,它可能会在翻转后结束)。您可以通过两种方式解决这个问题,或者使用GetTickCount64或简单地注意何时dwStartTicks > GetTickCount以及如果是,计算从多少毫秒dwStartTicks到翻转,以及从多少毫秒0到结果GetTickCount()并将这些数字加在一起(如果你能做到这一点,则加分以更聪明的方式)。

或者,您可以使用该clock功能。您可以在http://msdn.microsoft.com/en-us/library/4e2ess30(v=vs.71).aspx找到更多相关信息,包括如何使用它的示例,并且应该相当容易适应并集成到您的代码中。

最后,如果您对更“标准”的解决方案感兴趣,可以使用<chrono>C++ 标准库中的内容。查看http://en.cppreference.com/w/cpp/chrono以获取示例。

于 2013-03-21T20:39:28.613 回答
0

我认为增强计时器是您的最佳解决方案。

您可以像这样检查经过的时间:

#include <boost/timer.hpp>
int main() {   
boost::timer t; // start timing
 ...
 double elapsed_time = t.elapsed();
 ...
}
于 2013-03-21T20:40:02.290 回答