C++循环递增延时

C++循环递增延时,程序间隔一定时间读取一次数据,如果有数据,那么默认延时1S,如果没有数据,延时增加,直到增加到最大值为止,或者读取数据花费了两倍的限制时间等条件重置延时时长。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <time.h>
#include <iostream>
using namespace std;
 
void delay(int seconds){
    clock_t start = clock();
    clock_t lay = (clock_t)seconds*CLOCKS_PER_SEC;
    while((clock()-start)<lay)
    ;
}
int main(){
    static int delay_time=1;
    const unsigned int max_wait_time=5;//seconds
    clock_t start = clock();
    while(true){
        start = clock();
 
        //function place here begin
        //your can use i for example as run(&i); to get the value i
        //that suppose the function run have got a result
        int i=1;
        //cout<<"input:"<<endl;
        //cin>>i;
        //cout<<"output:"<<i<<endl;
        //if i is zero,reset delay time
        //function place here end
 
        if ( (clock()-start) < delay_time*CLOCKS_PER_SEC && delay_time < max_wait_time){
            delay_time++;
            cout<<"s++\n";
        }
 
        //reset condition, may can use one condition for this
        if ( (clock()-start) > 2*max_wait_time*CLOCKS_PER_SEC or i==0){
            delay_time=1;
            cout<<"s=1\n";
        }
        cout<<"delay "<<delay_time<<" seconds.\n";
        delay(delay_time);
    }
    return 0;
}

-EOF-