开发者

Timer\Counter in C for rate calculation?

Need a running (moving, rolling) average algorithm to calculate the 5-minute average bits that are passed in. All I have to work with is开发者_开发技巧 an accumulative value for the bits that are passed in.

For example: I start with 0 bits, 5 minutes later, I have 10 bits, so my average is 10 bits. 5 minutes later, I have 15 bits, so now my average is 7.5 bits. Another 5 minutes later, I have 30 bits, so my average now is 10.8 bits.

My question is, how can I implement a timer\counter in C++ so it would poll the bits value in exact 5 minutes intervals? Obviously I can't use delay 300 seconds. But can I make a timer in the background which would only fire an event (poll the bit value) every 5 minutes?


The Code to my Previous Answer

#define REENTRANT
//The above is neccessary when using threads. This must be defined before any includes are made
//Often times, gcc -DREENTRANT is used instead of this, however, it produces the same effect

#include <pthread.h>

char running=1;

void* timer(void* dump){
    unsigned char i=0;
    while(running){
        for(i=0;i<300 && running;i++){
            sleep(1);//so we don't need to wait the 300 seconds when we want to quit
        }
        if(running)
           callback();//note that this is called from a different thread from main()
    }
    pthread_exit(NULL);
}

    int main(){
    pthread_t thread;
    pthread_create(&thread,NULL,timer,NULL);
    //do some stuff
    running=0;
    pthread_join(thread,NULL);//we told it to stop running, however, we might need to wait literally a second
    pthread_exit(NULL);
    return 0;
}


The "dumb" solution is to use POSIX threads. You can make a thread and then put it in an infinite loop with sleep() in it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜