Pergunta

I'm using Visual Studio 2012 and C++, I need to call a function every 5 minutes, I've managed to do it but it consumes 25% of my CPU which is far from ideal.

The code is as follows,

time_t start;
time_t end;
time(&start);
while (1) {
time(&end);
double dif = difftime (end,start);
if (dif >= 300) { autofunction(); time(&start);} else {} }

Is there a more CPU efficient way to go about calling a function every 5 minutes or any way to slow down my while loop?

Any guidance will be greatly appreciated.

Foi útil?

Solução

Windows has Sleep(), and for something that happens every 300 seconds, that's perfectly good. There are also timers in Windows, which potentially takes a timerproc argument, which is a function - but note that this is a C function, not C++, so it mustn't be a class member function unless it is a static one.

Outras dicas

Since nobody suggested that, you can just spawn a new std::thread and Sleep in it.

What you do is busy waiting. You constantly check for the time being elapsed and so use up the CPU time.

Since you're on windows, Using Timer Queues might be of interest.

This creates a timer with a callback function. You can do other work, while waiting for the timer to expire.

I think the best answer will depend on some more of the details of what you're doing. If you only need it to be approximately 5 minutes, maybe you can put the duration-elapsed calculation at a more programmatically convenient location, and you'll run the task the first time after 5 minutes when you check.

Otherwise, it seems like @BartekBanachewicz has the best suggestion of starting a thread, which uses sleep---without blocking your main thread doing whatever you're doing. As long as your main thread will definitely be running longer than 5 minutes, it shouldn't be a problem to always re-join() the thread at the end, or whenever.

Using thread's has the benefit of not requiring any windows specific stuff -- e.g. @OlafDietsche's suggestion, whatever Timer Queues are. With c++0x, threads are super-easy to use, see: http://en.cppreference.com/w/cpp/thread/thread; http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-1-starting-threads.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top