How to use sleep in C

3 Answers

0 votes
// POSIX (Linux, macOS, Unix)

#include <stdio.h>
#include <time.h>
#include <unistd.h>
 
int main() {
    time_t t = time(NULL);
     
    printf("%s", ctime(&t));
 
    sleep(5);
 
    t = time(NULL);
    
    printf("%s", ctime(&t));
 
    return 0;
}
 
 
 
 
/*
run:
 
Mon May 30 05:42:09 2022
Mon May 30 05:42:14 2022
 
*/

 



answered Oct 5, 2021 by avibootz
edited 1 day ago by avibootz
0 votes
// usleep() — POSIX (microseconds)
// microseconds (1,000,000 µs = 1 second).

#include <stdio.h>
#include <unistd.h>   // for usleep()

int main() {
    printf("Sleeping for 500 milliseconds...\n");
    
    usleep(500000);   // 500,000 µs = 0.5 seconds
    
    printf("Done!\n");
    
    return 0;
}


/* 
run:

Sleeping for 500 milliseconds...
Done!

*/

 



answered 1 day ago by avibootz
0 votes
// Portable C11 method: thrd_sleep()
// If your compiler supports C11 threads (<threads.h>).

#include <stdio.h>
#include <threads.h>

int main() {
    struct timespec ts = {1, 500000000}; // 1.5 seconds
    
    printf("Sleeping for 1.5 seconds...\n");
    
    thrd_sleep(&ts, NULL);
    
    printf("Done!\n");
    
    return 0;
}


/* 
run:

Sleeping for 1.5 seconds...
Done!

*/

 



answered 1 day ago by avibootz

Related questions

1 answer 156 views
1 answer 118 views
118 views asked Sep 1, 2024 by avibootz
1 answer 100 views
100 views asked Sep 1, 2024 by avibootz
1 answer 112 views
112 views asked Sep 1, 2024 by avibootz
1 answer 92 views
92 views asked Sep 1, 2024 by avibootz
1 answer 109 views
109 views asked Sep 1, 2024 by avibootz
1 answer 109 views
109 views asked May 29, 2022 by avibootz
...