Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

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 May 1 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 May 1 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 May 1 by avibootz

Related questions

1 answer 187 views
1 answer 142 views
142 views asked Sep 1, 2024 by avibootz
1 answer 122 views
122 views asked Sep 1, 2024 by avibootz
1 answer 139 views
139 views asked Sep 1, 2024 by avibootz
1 answer 134 views
134 views asked Sep 1, 2024 by avibootz
1 answer 125 views
125 views asked Sep 1, 2024 by avibootz
1 answer 127 views
127 views asked May 29, 2022 by avibootz
...