implement time delay in c

后端 未结 17 1908
我在风中等你
我在风中等你 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:07

    // Provides ANSI C method of delaying x milliseconds

    #include 
    #include 
    #include 
    
    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();
    }
    

提交回复
热议问题