I am trying to write a simple c++ function sleep(int millisecond) that will sleep the program for user-specific millisecond.
Here is my code:
#include <iostream>
#include <time.h>
using namespace std;
void sleep(unsigned int mseconds) {
clock_t goal = mseconds + clock();
while (goal > clock());
}
int main() {
cout << "Hello World !" << endl;
sleep(3000);
cout << "Hello World 2" << endl;
}
The sleep() function works perfectly when I run this code on windows but doesn't work on Linux. Can anyone figure it out what's wrong with my code?
I don't know why everyone is dancing around your question instead of answering it.
You are attempting to implement your own sleep-like function, and your implementation, while it does busy wait instead of sleeping in the kernelspace (meaning that processor will be "actively" running code to sleep your program, instead of telling the machine your program is sleeping and it should run other code), is just fine.
The problem is that clock() is not required to return milliseconds. clock() will return system time/process time elapsed in ticks from epoch. What unit that time will take depends on the implementation.
For instance, on my machine, this is what the man page says:
DESCRIPTION
The clock() function determines the amount of processor time used since
the invocation of the calling process, measured in CLOCKS_PER_SECs of a
second.
RETURN VALUES
The clock() function returns the amount of time used unless an error
occurs, in which case the return value is -1.
SEE ALSO
getrusage(2), clocks(7)
STANDARDS
The clock() function conforms to ISO/IEC 9899:1990 (``ISO C90'') and
Version 3 of the Single UNIX Specification (``SUSv3'') which requires
CLOCKS_PER_SEC to be defined as one million.
As you can see from the bolded part, a tick is one-one-millionth of a second, aka a microsecond (not a millisecond). To "sleep" for 3 seconds, you'll need to call your sleep(3000000) and not sleep(3000).
With C++11 you can use sleep_for.
#include <chrono>
#include <thread>
void sleep(unsigned int mseconds) {
std::chrono::milliseconds dura( mseconds);
std::this_thread::sleep_for( dura );
}
You can use build-in sleep() function which takes pospond time as seconds not in milliseconds and have to include unistd.h standard library as build-in sleep() function is defined under this library.
Try it:
#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
cout << "Hello World !" << endl;
sleep(3); //wait for 3 seconds
cout << "Hello World 2" << endl;
}
:P
There is no standard C API for milliseconds on Linux so you will have to use usleep. POSIX sleep takes seconds.
Related
I have to write a stopwatch class in c++. The way I am trying to do this is by defining a variable to save laps (named 'time') and a bool that I use to see if the watch is started or stopped. When entering a char the timer should start and set time1. When another char is entered the bool switches to false and sets time2 and then prints time2-time1. This should be repeatable until 'n' is entered
I also am not quite sure I understand what unit of time time_t is in. In my code i get a return value of ±40 units every time i try to measure the interval of a lap, which I am guessing is the runtime of the program and not actually the time of the interval.
#ifndef stoppuhr_hpp
#define stoppuhr_hpp
#include <iostream>
#include <time.h>
class Stoppuhr{
private:
bool running;
clock_t time;
public:
void pushButtonStartStop () {
char t=0;
running=false;
time=0;
std::cout << "to start/stop watch please press a key, to end
clock type 'n' " << std::endl;
clock_t time1=0;
clock_t time2=0;
std::cout << time;
while (t!='n') {
std::cin >> t;
running= !running;
if (running) {
time1=clock();
}
else {
time2=clock();
time+=time2-time1;
std::cout << time << std::endl;
}
}
}
};
#endif /* stoppuhr_hpp */
I also am not quite sure I understand what unit of time time_t is in.
The unit of time represented by time_t is implementation specified. Usually, it represents seconds, as specified by POSIX.
However, you don't use time_t anywhere in your program.
I am guessing is the runtime of the program
I recommend not to guess, but to read documentation instead. clock() returns the processor time used by the program since some point in time. So deducting two timepoints returned by clock() will give you the processor time used between those timepoints. The unit of clock_t is 1 / CLOCKS_PER_SEC seconds.
i get a return value of ±40 units every time
Granularity of clock is implementation specified. It might be 40 units on your system. The program consumes hardly any processor time while it waits for input.
I have to write a stopwatch class
Stopwatches typically measure real world time i.e. wall clock time. Measuring processor time would be futile for this task.
I recommend using std::chrono::steady_clock::now instead.
If you insist on using time.h, then you can use time(nullptr) to get the wall clock time but I don't recommend it.
What is the simplest and cleanest way to get the time since execution of the program (with milliseconds precision) in C++ ?
I am making a wave interference simulator to produce Lissajous curves in C++. It requires the time since execution of the program (with at least milliseconds precision) to function. I can't seem to find any clean and simple way to do it after a bit of research.
All <chrono> functions seem very confusing to me. Similar questions on here on Stack Overflow seem to be either unrelated, confusing (to me) or inapplicable for my situation. I tried using functions from <time.h>, only to discover that they have precision upto seconds only.
I am running Windows 7 x64. The program need not be platform independent as it's for personal use.
Any help is greatly appreciated.
Thank you!
The new <chrono> functions take a little getting used to but they make things fairly easy when you get to know how they work.
Your problem could be solved like this for example:
#include <chrono>
#include <thread>
#include <iostream>
// for readability
using hr_clock = std::chrono::high_resolution_clock;
using hr_time_point = hr_clock::time_point;
using hr_duration = hr_clock::duration;
using milliseconds = std::chrono::milliseconds;
int main()
{
// note the program start time
hr_time_point prog_start = hr_clock::now();
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
// find the duration
hr_duration d = hr_clock::now() - prog_start;
// cast the duration to milliseconds
milliseconds ms = std::chrono::duration_cast<milliseconds>(d);
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.\n";
}
For convenience you could create a function to return the time since that function was last called:
milliseconds since_last_call()
{
// retain time between calls (static)
static hr_time_point previous = hr_clock::now();
// get current time
hr_time_point current = hr_clock::now();
// get the time difference between now and previous call to the function
milliseconds ms = std::chrono::duration_cast<milliseconds>(current - previous);
// store current time for next call
previous = current;
// return elapsed time in milliseconds
return ms;
}
int main()
{
since_last_call(); // initialize functions internal static time_point
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
milliseconds ms = since_last_call();
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.\n";
}
I'm experiencing strange issues with boost::sleep() function. I have this basic code:
#include <sys/time.h>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
void thread_func()
{
timeval start, end;
gettimeofday( &start, NULL );
boost::this_thread::sleep( boost::posix_time::milliseconds(1) ); // usleep(1000) here works just fine.
gettimeofday( &end, NULL );
int secs = end.tv_sec - start.tv_sec;
int usec = end.tv_usec - start.tv_usec;
std::cout << "Elapsed time: " << secs << " s and " << usec << " us" << std::endl;
}
int main()
{
thread_func();
boost::thread thread = boost::thread( thread_func );
thread.join();
return 0;
}
The problem is that the boost::sleep() functions behaves differently in the created thread and in the main one. The output of this program is
Elapsed time: 0 s and 1066 us
Elapsed time: 0 s and 101083 us
i.e. the boost::sleep() function sleeps for 100 milliseconds in the created thread, whereas it works okay in the main thread (it sleeps for 1 ms). If I'm inside a created thread, I can't get the accuracy below 100 ms (for example by using boost::posix_time::microseconds). However, if I use usleep(1000), it works just fine.
I'm using Fedora 18 (64-bit) 3.8.4 & Boost 1.50.0-5.fc18 on Intel i7 CPU. I also tested the code on different PC with Win 7 & Boost 1.48.0 and the problem does not occur, so I guess it should be related to the system configuration, but I have no clue how.
boost::this_thread::sleep is deprecated (see docs).
usleep is also deprecated (obsolete in POSIX.1-2001 and removed from POSIX.1-2008).
FWIW, in the older (1.44) boost headers I have installed locally, the relative delay version of boost::this_thread_sleep actually calls gettimeofday to calculate the absolute deadline, and then forwards to the absolute version (which is compiled out-of-line, so I don't have it handy). Note that gettimeofday was also marked obsolete in POSIX.1-2008.
The suggested replacements for all these are:
boost::this_thread::sleep_for instead of ...::sleep with a relative delay
boost::this_thread::sleep_until instead of ...::sleep with an absolute time
nanosleep instead of usleep
clock_gettime instead of gettimeofday
Be aware, that calling boost::this_thread::sleep() and related methods not only puts the thread to sleep but asks the scheduler to give the CPU to another thread that is ready for execution. So you are acutally measuring the maximum of the time of the sleep OR the time until the thread gets the CPU again.
I have found the usleep function in unistd.h, and I thought it was useful to wait some time before every action.But I have discovered that the thread just sleeps if it it doesn't receive any signal.For example if I press a button (I'm using OpenGL but the question is more specific about time.h and unistd.h), the thread gets awaken and I'm not getting what I want.
In time.h there is the sleep function that accepts an integer but an integer is too much ( I want to wait 0.3 seconds), so I use usleep.
I ask if there is a function to take time in milliseconds (from any GNU or whatever library).
It should work like time(), but returning milliseconds instead of seconds.Is that possibile?
If you have boost you can do it this way:
#include <boost/thread.hpp>
int main()
{
boost::this_thread::sleep(boost::posix_time::millisec(2000));
return 0;
}
This simple example, as you can see in the code, sleeps for 2000ms.
Edit:
Ok, I thought I understood the question but then I read the comments and now I'm not so sure anymore.
Perhaps you want to get how many milliseconds that has passed since some point/event? If that is the case then you could do something like:
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <iostream>
int main()
{
boost::chrono::high_resolution_clock::time_point start = boost::chrono::high_resolution_clock::now();
boost::this_thread::sleep(boost::posix_time::millisec(2000));
boost::chrono::milliseconds ms = boost::chrono::duration_cast<boost::chrono::milliseconds> (boost::chrono::high_resolution_clock::now() - start);
std::cout << "2000ms sleep took " << ms.count() << "ms " << "\n";
return 0;
}
(Please excuse the long lines)
This is a cross-platform function I use:
unsigned Util::getTickCount()
{
#ifdef WINDOWS
return GetTickCount();
#else
struct timeval tv;
gettimeofday(&tv, 0);
return unsigned((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
#endif
}
I need to know how create a timer or measure out 500ms in C++ in a linux environment. I have tried using gettimeofday and using the time structure but cant get the correct precision for milliseconds. What I am trying to do is have an operation continue for a max of 500ms...after 500ms something else happens.
If you have access to C++11 then your best bet it to use std::chrono library
http://en.cppreference.com/w/cpp/chrono/duration
I aren't entirely sure what you want to do with it do you want to wait for exactly 500ms?
you can so this for that
std::this_thread::sleep_for(std::chrono::milliseconds(500));
you can do an operation until 500 milliseconds has elapsed by getting a time pointer and check to see whether timepoint - system_time::now() is greater than 500ms
//if you compiler supports it you can use auto
std::chrono::system_clock::time_point start=std::chrono::system_clock::now();
while(start-std::chrono::system_clock::now()
< std::chrono::milliseconds(500))
{
//do action
}
If you don't have C++11 this will also work with boost chrono library. The advantage of this approach is that it is portable unlike using linux time functions.
Your question isn't really clear about why you "can't get the correct precision" or what happens when you try to do that, but if you're having trouble with gettimeofday, consider using clock_gettime instead. man clock_gettime for details.
Since you are in Linux, you can use the system call usleep
int usleep(useconds_t usec);
Which will let your process sleep for some microseconds period.
#include <chrono>
#include <iostream>
#include <future>
#include <atomic>
void keep_busy(std::chrono::milliseconds this_long,std::atomic<bool> *canceled) {
auto start = std::chrono::high_resolution_clock::now();
while(std::chrono::high_resolution_clock::now() < start+this_long) {
std::cout << "work\n";
std::this_thread::sleep_for(std::chrono::milliseconds(50));
if(canceled->load()) {
std::cout << "canceling op\n";
throw "operation canceled";
}
}
}
int main() {
std::atomic<bool> canceled(false);
auto future = std::async(std::launch::async,
keep_busy,std::chrono::milliseconds(600),&canceled);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
canceled.store(true);
try {
future.get();
std::cout << "operation succeded\n";
} catch( char const *e) {
std::cout << "operation failed due to: " << e << '\n';
}
}
I'm not entirely sure this is correct...