Count seconds in the background (Python)

Updated vegaseat 0 Tallied Votes 9K Views Share

Use Python module threading to count intervals (in seconds) in the background. You can use this to time any relatively slow event like the time it took to finish a game or play some music. You can also peek at the current interval value as the event goes on. Go ahead and explore.

Just an example how to run time.sleep() in a thread.

''' threading_count_seconds1.py
count seconds needed to complete a task
counter runs in the background

tested with Python27 and Python33  by  vegaseat  19sep2014
'''

import threading
import time
import sys

# make this work with Python2 or Python3
if sys.version_info[0] < 3:
    input = raw_input


class SecondCounter(threading.Thread):
    '''
    create a thread object that will do the counting in the background
    default interval is 1/1000 of a second
    '''
    def __init__(self, interval=0.001):
        # init the thread
        threading.Thread.__init__(self)
        self.interval = interval  # seconds
        # initial value
        self.value = 0
        # controls the while loop in method run
        self.alive = False

    def run(self):
        '''
        this will run in its own thread via self.start()
        '''
        self.alive = True
        while self.alive:
            time.sleep(self.interval)
            # update count value
            self.value += self.interval

    def peek(self):
        '''
        return the current value
        '''
        return self.value

    def finish(self):
        '''
        close the thread, return final value
        '''
        # stop the while loop in method run
        self.alive = False
        return self.value


# create the class instance
count = SecondCounter()

# start the count
count.start()

# test the counter with a key board response time
# or put your own code you want to background-time in here
# you can always peek at the current counter value
e = input("Press Enter")
e = input("Press Enter again")

# stop the count and get elapsed time
seconds = count.finish()

print("You took {} seconds between Enter actions".format(seconds))
HiHe 174 Junior Poster

Works well with Python34

Gribouillis 1,391 Programming Explorer Team Colleague

You can reach the same result without a thread. Can you explain why you start a thread ? Here is my code

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from datetime import datetime
import sys

# make this work with Python2 or Python3
if sys.version_info[0] < 3:
    input = raw_input


class SecondCounter(object):
    def __init__(self):
        self.start_time = None

    def start(self):
        self.start_time = datetime.now()

    @property
    def value(self):
        return (datetime.now() - self.start_time).total_seconds()

    def peek(self):
        return self.value

    def finish(self):
        return self.value


# create the class instance
count = SecondCounter()

# start the count
count.start()

# test the counter with a key board response time
# or put your own code you want to background-time in here
# you can always peek at the current counter value
e = input("Press Enter")
e = input("Press Enter again")

# stop the count and get elapsed time
seconds = count.finish()

print("You took {} seconds between Enter actions".format(seconds))
Lardmeister 461 Posting Virtuoso

Why bother with a class?

from datetime import datetime as dt

# make this work with Python2 or Python3
try: input = raw_input
except: pass

# start the count
start = dt.now()

# test the counter with a key board response time
# or put your own code you want to background-time in here
# you can always peek at the current counter value
e = input("Press Enter")
e = input("Press Enter again")

# get elapsed time
seconds = (dt.now() - start).total_seconds()

print("You took {} seconds between Enter actions".format(seconds))
Lardmeister 461 Posting Virtuoso

For higher precision one could use
time.perf_counter() which is new in Python 3.3

Oh I see, you may want to peek.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sorry, this was supposed to be an example of a class inheriting threading.
If you are looking for an interruptable sleep() function, use threading.Timer().

Member Avatar for Viresh_2
Viresh_2

I had a slight issue with this on python 3.5 . the end time would show 86 seconds but i timed it and it was actually 2 minutes.

Anyone know how to solve!!!!!!!!!!!!!!!!!!!!!!!!!!11111

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.