timer function - how to improve?

I don't feel so comfortable using the following code I wrote. How can I make it better?

1
2
3
4
5
6
7
8
9
10
11
#include <time.h>
  void timer(int interval){
    clock_t timeInit = clock();
    while(true){
    clock_t timeTest = clock();
        if(timeTest - timeInit == interval){
            std::cout<<"stuff happened"<<std::endl;
            break;
        }
    }
}

this is my timer function and I use it as the following

1
2
3
4
5
6
7
8
9
int main()
{
while(true){
    timer(1000);
    //do stuff
}

 return 0;
}
Well what are you trying to do in the meantime?

It burns 100% of the CPU at the moment.

Also, your exit condition should be
if(timeTest - timeInit >= interval)
There's no reason to assume that clock() returns a monotonic +1 value.
If the value were to increase by +2 at the wrong moment, you could miss the == test completely.

From the manual page.

Note that the time can wrap around. On a 32-bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.

So you also need to take into account when timeTest < timeInit, and act accordingly.
Well what are you trying to do in the meantime?

It burns 100% of the CPU at the moment.

Also, your exit condition should be
if(timeTest - timeInit >= interval)
There's no reason to assume that clock() returns a monotonic +1 value.
If the value were to increase by +2 at the wrong moment, you could miss the == test completely.

From the manual page.

Note that the time can wrap around. On a 32-bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.

So you also need to take into account when timeTest < timeInit, and act accordingly.




In the meantime my server sends messages to clients every second, what I try do is receive messages on a given time interval. The code works, I'm doing what I intended to do , but in a dirty, dirty way. Burns the entire CPU as you said.

I'll make changes according to your suggestions and edit.
Last edited on
Your program loops as long as 'interval' endures through your while loop.
If you want to save CPU power, you could make your program sleep for some time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <chrono>
#include <iostream>
#include <thread>

void timer( int ms)
{
    std::this_thread::sleep_for( std::chrono::milliseconds( ms));
    std::cout << "stuff happend" << std::endl;
}

int main()
{
    std::cout << "Starting timer:\n";
    timer( 3000);
}

http://www.cplusplus.com/reference/thread/this_thread/sleep_for/
Topic archived. No new replies allowed.