Skip to content

Timer#

Timer(thread=None, decimals=2) #

Main class to create a Timer instance. If not using the class with a with statement as context manager, remember that a timer.start() should always be followed by timer.stop() later in the code.

Parameters:

Name Type Description Default
thread str | None

Option to start new thread.

None
decimals int | None

Option to define decimals for output. Minimum 0 (for no decimals) and maximum 9. If None, default is 2 decimals. May be overruled in certain cases due to humanised output.

2
Example

Basic usage:

Python
1
2
3
4
5
6
7
8
from timer import Timer

timer = Timer()
timer.start()

# Insert your code here

timer.stop()

Or with a with statement as context manager:

Python
1
2
3
4
from timer import Timer

with Timer():
    # Insert your code here

In both cases, the terminal output example is the same:

Elapsed time: 12.34 seconds

With custom thread name and decimals:

Python
1
2
3
4
5
6
7
8
from timer import Timer

timer = Timer(thread="my_thread", decimals=5)
timer.start()

# Insert your code here

timer.stop(thread="my_thread")

Or with a with statement as context manager:

Python
1
2
3
4
from timer import Timer

with Timer(thread="my_thread", decimals=5):
    # Insert your code here

As before, the terminal will output the same result in both cases:

Elapsed time: 0.12345 seconds for thread MY_THREAD

start(thread=None, decimals=None) #

Starts the Timer. Should always be followed by timer.stop() later in the code.

Parameters:

Name Type Description Default
thread str | None

Option to start new thread.

None
decimals int | None

Option to define decimals for output. Minimum 0 (for no decimals) and maximum 9. If None, default is 2 decimals. May be overruled in certain cases due to humanised output.

None
Example

Basic usage:

Python
1
2
3
4
5
6
7
8
from timer import Timer

timer = Timer()
timer.start()

# Insert your code here

timer.stop()

Terminal output example:

Elapsed time: 12.34 seconds

With custom thread name and decimals:

Python
1
2
3
4
5
6
7
8
from timer import Timer

timer = Timer()
timer.start(thread="my_thread", decimals=5)

# Insert your code here

timer.stop(thread="my_thread")

Terminal output example:

Elapsed time: 0.12345 seconds for thread MY_THREAD

stop(thread=None) #

Stops the Timer. Should always be called after timer.start().

Parameters:

Name Type Description Default
thread str | None

Option to stop specific thread.

None
Example

Basic usage:

Python
1
2
3
4
5
6
7
8
from timer import Timer

timer = Timer()
timer.start()

# Insert your code here

timer.stop()

Terminal output example:

Elapsed time: 12.34 seconds

With custom thread name and decimals:

Python
1
2
3
4
5
6
7
8
from timer import Timer

timer = Timer()
timer.start(thread="my_thread", decimals=5)

# Insert your code here

timer.stop(thread="my_thread")

Terminal output example:

Elapsed time: 0.12345 seconds for thread MY_THREAD