implement time delay in c

后端 未结 17 1760
我在风中等你
我在风中等你 2020-11-30 05:43

I don\'t know exactly how to word a search for this.. so I haven\'t had any luck finding anything.. :S

I need to implement a time delay in C.

for example I w

相关标签:
17条回答
  • 2020-11-30 06:02

    Is it timer?

    For WIN32 try http://msdn.microsoft.com/en-us/library/ms687012%28VS.85%29.aspx

    0 讨论(0)
  • 2020-11-30 06:07

    // Provides ANSI C method of delaying x milliseconds

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    void delayMillis(unsigned long ms) {
        clock_t start_ticks = clock();
        unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
        while (clock()-start_ticks < ms*millis_ticks) {
        }
    }    
    
    /* 
     * Example output:
     * 
     * CLOCKS_PER_SEC:[1000000]
     * 
     * Test Delay of 800 ms....
     * 
     * start[2054], end[802058], 
     * elapsedSec:[0.802058]
     */
    int testDelayMillis() {
    
        printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
        clock_t start_t, end_t;
        start_t = clock();
        printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
        delayMillis(800); 
        end_t = clock();
        double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
        printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);
    
    }
    
    int main() {    
        testDelayMillis();
    }
    
    0 讨论(0)
  • 2020-11-30 06:10

    you can simply call delay() function. So if you want to delay the process in 3 seconds, call delay(3000)...

    0 讨论(0)
  • 2020-11-30 06:15

    What operating system are you using?
    I know that on windows, you can do something like this:

    //include crap
    #include <windows.h>
    
    int main () {
      //do things
      Sleep(/* ur wait time in ms */);// wait for param1 ms
      //continue to do things
    }
    
    0 讨论(0)
  • 2020-11-30 06:16

    Try sleep(int number_of_seconds)

    0 讨论(0)
  • 2020-11-30 06:16

    C11 has a function specifically for this:

    #include <threads.h>
    #include <time.h>
    #include <stdio.h>
    
    void sleep(time_t seconds) {
        struct timespec time;
        time.tv_sec = seconds;
        time.tv_nsec = 0;
        while (thrd_sleep(&time, &time)) {}
    }
    
    int main() {
        puts("Sleeping for 5 seconds...");
        sleep(5);
        puts("Done!");
        return 0;
    }
    

    Note that this is only available starting in glibc 2.28.

    0 讨论(0)
提交回复
热议问题