Reputation: 19
I'm trying to figure out how to calculate time in c++ . I'm making a program where every 3 seconds an event happens for example print out "hello" etc;
Upvotes: 1
Views: 891
Reputation: 3912
Here's an example using two threads so your program won't freeze and this_thread::sleep_for()
in C++11:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
void hello()
{
while(1)
{
cout << "Hello" << endl;
chrono::milliseconds duration( 3000 );
this_thread::sleep_for( duration );
}
}
int main()
{
//start the hello thread
thread help1(hello);
//do other stuff in the main thread
for(int i=0; i <10; i++)
{
cout << "Hello2" << endl;
chrono::milliseconds duration( 3000 );
this_thread::sleep_for( duration );
}
//wait for the other thread to finish in this case wait forever(while(1))
help1.join();
}
Upvotes: 3
Reputation: 707
It is dependent on your OS/Compiler.
Case 1:
If you have C++11 then you can use as suggested by Chris:
std::this_thread::sleep_for() // You have to include header file thread
Case 2:
If you are on the windows platform then you can also use something like:
#include windows.h
int main ()
{
event 1;
Sleep(1000); // number is in milliseconds 1Sec = 1000 MiliSeconds
event 2;
return 0;
}
Case 3:
On linux platform you can simply use:
sleep(In seconds);
Upvotes: 0
Reputation: 29724
you can use boost::timer
to calculate time in C++:
using boost::timer::cpu_timer;
using boost::timer::cpu_times;
using boost::timer::nanosecond_type;
...
nanosecond_type const three_seconds(3 * 1000000000LL);
cpu_timer timer;
cpu_times const elapsed_times(timer.elapsed());
nanosecond_type const elapsed(elapsed_times.system + elapsed_times.user);
if (elapsed >= three_seconds)
{
//more then 3 seconds elapsed
}
Upvotes: 1