implement time delay in c

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

    Here is how you can do it on most desktop systems:

    #ifdef _WIN32
        #include 
    #else
        #include 
    #endif
    
    void wait( int seconds )
    {   // Pretty crossplatform, both ALL POSIX compliant systems AND Windows
        #ifdef _WIN32
            Sleep( 1000 * seconds );
        #else
            sleep( seconds );
        #endif
    }
    
    int
    main( int argc, char **argv)
    {
        int running = 3;
        while( running )
        {   // do something
            --running;
            wait( 3 );
        }
        return 0; // OK
    }
    

    Here is how you can do it on a microcomputer / processor w/o timer:

    int wait_loop0 = 10000;
    int wait_loop1 = 6000;
    
    // for microprocessor without timer, if it has a timer refer to vendor documentation and use it instead.
    void
    wait( int seconds )
    {   // this function needs to be finetuned for the specific microprocessor
        int i, j, k;
        for(i = 0; i < seconds; i++)
        {
            for(j = 0; j < wait_loop0; j++)
            {
                for(k = 0; k < wait_loop1; k++)
                {   // waste function, volatile makes sure it is not being optimized out by compiler
                    int volatile t = 120 * j * i + k;
                    t = t + 5;
                }
            }
        }
    }
    
    int
    main( int argc, char **argv)
    {
        int running = 3;
        while( running )
        {   // do something
            --running;
            wait( 3 );
        }
        return 0; // OK
    }
    

    The waitloop variables must be fine tuned, those did work pretty close for my computer, but the frequency scale thing makes it very imprecise for a modern desktop system; So don't use there unless you're bare to the metal and not doing such stuff.

提交回复
热议问题