How to make a timer program in Python

前端 未结 11 2269
予麋鹿
予麋鹿 2021-02-08 14:24

Here is my goal: To make a small program (text based) that will start with a greeting, print out a timer for how long it has been since the last event, and then a timer for the

11条回答
  •  猫巷女王i
    2021-02-08 15:03

    Use the timeit module to time your code. Then adjust the time.sleep(x) accordingly. For example, you could use one of the following:

    import timeit
    #Do all your code and time stuff and while loop
    #Store that time in a variable named timedLoop
    timer = 1- timedLoop
    
    #Inside while loop:
       time.sleep(timer)
    

    This will time the code you have other than the time.sleep, and subtract that from 1 second and will sleep for that amount of time. This will give an accurate representation of 1 second. Another way is less work, but may not be as accurate:

    #set up timeit module in another program and time your code, then do this:
    #In new program:
    timer = 1 - timerLoop
    print timerLoop
    

    Run your program, then copy the printed time and paste it into program two, the one you have now. Use timerLoop in your time.sleep():

    time.sleep(timerLoop)
    

    That should fix your problem.

提交回复
热议问题