Search code examples
timeraspberry-pi2

Raspberry pi timer


I was hoping someone can help me because google searches are being frustrating and I am not getting anywhere.

What I need: Use simulated time from the pi and accelerometer readings to determine motion.

I am looking to set up a timer using the Raspberry Pi alone (standalone with no internet) I DO NOT want or need a RTC(or do I?). I just need to track time from when a program is initiated to when it completes in seconds.

Now the "time.sleep(...)" does not work, because it halts the program and real time is not simulated.

What code can I use to have a simulated timer that runs in the background from which I can track time as the program progresses?

Thanks


Solution

  • the time() method from the time module (time.time()) gives you the system time as seconds from epoch (1st January 1970). If you do not have an internet connection and no RTC, this will likely start from 0 everytime you boot the pi. However as you only care about relative time, this should be ok.

    You can store the value time.time() returns at the start of your program and subtract the start time from the current time (obtained by calling time.time() again) to get seconds elapsed at any point.

    eg:

    import time
    start = time.time()
    # do something here that takes time
    elapsed_seconds = time.time() - start
    

    alternatively, a better method is to install the uptime module. uptime.uptime() will return the time since the raspberry pi booted in seconds, which will always be monotonic increasing till the board shuts down.

    System time can be changed by an NTP client, etc... if present outside of your control, so it can break your code by the time changing between your invocations of time.time().