In my program I want to call a function for each second. Once the function has been called it should be called again after an exact second. Like this I want to call the function for each second.
How can this be done? I tried with the function clock() in <ctime> as well. It didn't work since it didn't allow me to measure the time duration of a second in an accurate manner.
Please help me on this.
1. modern compiler option: spawn a thread that runs an endless loop that sleeps for one second and calls your function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <thread>
#include <chrono>
void fn()
{
for(;;)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
// <-- call your function here
}
}
int main()
{
std::thread(fn).detach();
// <- do something that takes more than a second here
}
3. for completeness: use system-specific timer API (e.g. setitimer() on POSIX) and write a signal handler (e.g. SIGALRM on POSIX) that calls your function.
Note that all options have varying degrees of precision, and nothing gives the absolute "exact second".
#include <ctime>
usingnamespace std;
int main()
{
int a=clock()/CLOCKS_PER_SEC;//this gets the time in sec.
while(true)
{
while(clock()/CLOCKS_PER_SEC-a<1);
//call your function
a=clock()/CLOCKS_PER_SEC;
}
}