在c ++中优化时间(NULL)调用

Fli*_*man 1 c++ optimization

我有一个系统,它花费66%的时间在一个时间(NULL)调用.

有没有办法缓存或优化此调用?

上下文:我正在使用Protothread for c ++.尝试使用状态机模拟线程.所以我不能使用本机线程.

这是标题:

#ifndef __TIMER_H__
#define __TIMER_H__

#include <time.h>
#include <iostream>

class Timer
{
private:
    time_t initial;
public:
    Timer();
    unsigned long passed();
};

#endif
Run Code Online (Sandbox Code Playgroud)

和源文件:

#include "Timer.h"

using namespace std;

Timer::Timer()
{
    initial = time(NULL);
}

unsigned long Timer::passed()
{
    time_t current = time(NULL);
    return (current - initial);
}
Run Code Online (Sandbox Code Playgroud)

更新:最终解决方案!cpu在某个地方循环,如果我把它们用在正确的地方.毕竟这并不是那么糟糕.

#define start_timer() timer_start=time(NULL)
#define timeout(x)   ((time(NULL)-timer_start)>=x)

Pau*_*xon 8

我认为你在一些循环中调用它,否则效率很高.

你可以做的是保持循环在时间返回值变化之前经历的迭代次数.

然后不要再次调用它,直到你再次经历了那么多次迭代.

如果您发现自己正在漂泊,可以向上或向下动态调整此计数,但您应该能够设计它,以便平均每秒调用一次time().

这里有一个关于你如何做到这一点的大致想法(这个主题有很多变化)

int iterations_per_sec=10; //wild guess
int iterations=0;

while(looping)
{
    //do the real work

    //check our timing
    if (++iterations>iterations_per_sec)
    {
        int t=time(NULL);
        if (t==lasttime)
        {
            iterations_per_sec++;
        }
        else
        {
            iterations_per_sec=iterations/(t-lasttime);
            iterations=0;
            lastime=t;

            //do whatever else you want to do on a per-second basis
        }
    }

}
Run Code Online (Sandbox Code Playgroud)


Joh*_*itb 6

这听起来很多,因为它time只有1秒的精度.听起来你经常这么称呼它.一个可能的改进是可能每500ms只调用一次.所以它仍会每秒都会出现.

因此,不是每秒调用100次,而是每隔500毫秒启动一个定时器,占用当前时间并将其存储为整数.然后,每秒读取整数100次.