Is there a sleep function for float in C?


My question was if you knew any function that does the same thing as sleep for 0.5 or 0.25 seconds. That is, if there is something like sleep(0.25); since the function sleep does not work because it only applies to integers.

asked by Pedrogg 26.12.2016 в 19:40

3 answers


Ok for integers because it pauses with resolution of seconds , so why use another type of argument?

Fortunately, you have several options, all in the POSIX standard:

#include <unistd.h>

int usleep(useconds_t usec);

that uses microseconds , or

#include <time.h>

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

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

Note that it uses nanoseconds : 1000000 nanoseconds = 1 millisecond.

Notice that, in both cases, the accuracy will hardly be exactly as requested; you will always be at the mercy of the workload of the system, your hardware clock, ... That is, the pause will always be something greater than the one requested.


The usleep( ) function has been removed from the latest POSIX ; it is recommended to use the second, nanosleep( ) .

answered by 26.12.2016 / 20:39

Sleep() is a function that receives integer values to define the wait time in milliseconds. So if you want to define a fraction of a second, you should only calculate that fragment of time:

Sleep( 1000 ); // 1 segundo(1.0)
Sleep( 500 ); // 1/2 segundo (0.5)
Sleep( 250 ); // 1/4 segundo (0.25)

therefore, just multiply your decimal value by 1000:

Sleep( (0.25)*1000 ); // 250
answered by 26.12.2016 в 20:03

You could re-implement Sleep so that you work in seconds and not in milliseconds and where you can pass decimal numbers there

void  SleepEx(float seconds)
  DWORD miliSeconds=seconds*1000;

int main()
    cout<<"Programa terminado"<<endl;
answered by 26.12.2016 в 20:02