Operatins per second.

Hi, I have some small problem. I need to write some function in C++ witch should call some other function each next seconds. Is there any built in function for that in C++ ?

Thanks for any help.
Last edited on
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
#include <iostream>
#include <thread>
#include <chrono>
#include <functional>
#include <ctime>

void periodic_call( int period_in_milliseconds, int ntimes, std::function< void() > function  )  
{
    const auto period = std::chrono::milliseconds(period_in_milliseconds) ;
    std::chrono::milliseconds delta{} ;
    
    for( int i = 0 ; i < ntimes ; ++i )
    {
        std::this_thread::sleep_for( period - delta ) ;
        
        // assumes that the time taken to execute the function is less than period_in_milliseconds
        auto start = std::chrono::steady_clock::now() ;
        function() ;
        auto end = std::chrono::steady_clock::now() ;
        
        delta = std::chrono::duration_cast<std::chrono::milliseconds>(end-start) ;
    }
}

void foo( int a, int b )
{
    static int n = 0 ;
    static int c = 0 ;
    
    c = c*a + b ;
    auto t = std::time(nullptr) ;
    char now[128] ;
    std::strftime( now, sizeof(now), "  at %T\n", std::localtime(&t) ) ;
    std::cout << ++n << ". " << "foo::c ==  " << c << now << std::flush ;
}

int main()
{
    // launch a thread to call foo(2,3) once every 2 seconds, 5 times in all
    std::thread( periodic_call, 2000, 5, std::bind( foo, 2, 3 )  ).join() ;
}

http://coliru.stacked-crooked.com/a/f7474525215a3868
@ OP: The short answer is no. JLBorges solution would do what you are asking. I don't know why it was reported, it isn't a thread bomb or anything malicious since the number of executions is managed by the for loop. He could use some more documentation but that is certainly no reason to report him. What do you mean by "next seconds" by the way? Does the interval between the executions change?

P.S.: This kind of thing is better managed by the task scheduler on the OS.
Topic archived. No new replies allowed.