Sleep For Milliseconds

Sleep for milliseconds

Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for usleep, which accepts microseconds:

#include <unistd.h>

unsigned int microseconds;
...
usleep(microseconds);

Is there an alternative sleep function in C to milliseconds?

Yes - older POSIX standards defined usleep(), so this is available on Linux:

int usleep(useconds_t usec);

DESCRIPTION

The usleep() function suspends execution of the calling thread for
(at least) usec microseconds. The sleep may be lengthened slightly by
any system activity or by the time spent processing the call or by the
granularity of system timers.

usleep() takes microseconds, so you will have to multiply the input by 1000 in order to sleep in milliseconds.


usleep() has since been deprecated and subsequently removed from POSIX; for new code, nanosleep() is preferred:

#include <time.h>

int nanosleep(const struct timespec *req, struct timespec *rem);

DESCRIPTION

nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed, or the
delivery of a signal that triggers the invocation of a handler in the
calling thread or that terminates the process.

The structure timespec is used to specify intervals of time with nanosecond precision. It is defined as follows:

struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};

An example msleep() function implemented using nanosleep(), continuing the sleep if it is interrupted by a signal:

#include <time.h>
#include <errno.h>

/* msleep(): Sleep for the requested number of milliseconds. */
int msleep(long msec)
{
struct timespec ts;
int res;

if (msec < 0)
{
errno = EINVAL;
return -1;
}

ts.tv_sec = msec / 1000;
ts.tv_nsec = (msec % 1000) * 1000000;

do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);

return res;
}

why c++11 sleep_for microseconds actually sleep for millisecond?

You've got the question you asked covered by the other answers, but you also asked a question in the comments:

Is there any simple method can ensure i sleep for 1us?

Instead of calling sleep_for, yielding the thread's execution slot, you could busy-sleep. That is, loop until a certain amount of time has passed. It'll often get more accurate results at the cost of making that CPU thread unusable for doing anything else.

Here's one example with a function called busy_sleep():

// get a rough estimate of how much overhead there is in calling buzy_sleep()
std::chrono::nanoseconds calc_overhead() {
using namespace std::chrono;
constexpr size_t tests = 1001;
constexpr auto timer = 200us;

auto init = [&timer]() {
auto end = steady_clock::now() + timer;
while(steady_clock::now() < end);
};

time_point<steady_clock> start;
nanoseconds dur[tests];

for(auto& d : dur) {
start = steady_clock::now();
init();
d = steady_clock::now() - start - timer;
}
std::sort(std::begin(dur), std::end(dur));
// get the median value or something a little less as in this example:
return dur[tests / 3];
}

// initialize the overhead constant that will be used in busy_sleep()
static const std::chrono::nanoseconds overhead = calc_overhead();

inline void busy_sleep(std::chrono::nanoseconds t) {
auto end = std::chrono::steady_clock::now() + t - overhead;
while(std::chrono::steady_clock::now() < end);
}

Demo

Note: This was updated after it was accepted since I noticed that the overhead calculation could sometimes get terribly wrong. The updated example should be less fragile.

How do I get my program to sleep for 50 milliseconds?

Use time.sleep()

from time import sleep
sleep(0.05)

PHP - sleep() in milliseconds

This is your only pratical alternative: usleep - Delay execution in microseconds

So to sleep for two miliseconds:

usleep( 2 * 1000 );

To sleep for a quater of a second:

usleep( 250000 );

Note that sleep() works with integers, sleep(0.25) would execute as sleep(0) Meaning this function would finish immediatly.

$i = 0;
while( $i < 5000 )
{
sleep(0.25);
echo '.';
$i++;
}
echo 'done';

How do I sleep for a certain number of milliseconds?

The TimeSpan struct has some very useful methods for creating TimeSpans, you are looking for TimeSpan.FromSeconds

var timeToSleep = TimeSpan.FromSeconds(Convert.ToDouble(numericUpDown1.Value));

Thread.Sleep(timeToSleep);

If you are in an asynchronous method you can use:

await Task.Delay(timeToSleep);

If I sleep for 10 milliseconds. what do I need to increment by to get a second?

I would recommend using absolute time points and wait_until(). Something like this:

// steady_clock is more reliable than high_resolution_clock
auto const start_time = std::chrono::steady_clock::now();
auto const wait_time = std::chrono::milliseconds{10};
auto next_time = start_time + wait_time; // regularly updated time point

for(;;)
{
// wait for next absolute time point
std::this_thread::sleep_until(next_time);
next_time += wait_time; // increment absolute time

// Use milliseconds to get to seconds to avoid
// rounding to the nearest second
auto const total_time = std::chrono::steady_clock::now() - start_time;
auto const total_millisecs = double(std::chrono::duration_cast<std::chrono::milliseconds>(total_time).count());
auto const total_seconds = total_millisecs / 1000.0;

std::cout << "seconds: " << total_seconds << '\n';
}


Related Topics



Leave a reply



Submit