Why Use Multiple Threads?#
Imagine that you want to troubleshoot which parts of your code are performing better or worse. Or do you want to split-test the performance of different methods? Then you need flexibility, and Timer for Python is a quick, easy way to get the job done.
Examples#
With Context Manager#
To measure the performance of multiple blocks of code, use the thread
parameter to name different threads:
Python | |
---|---|
How it appears in the terminal:
% Elapsed time: 0.12345 seconds for thread B
% Elapsed time: 6.78 seconds for thread A
Singleton and Unique Threads
The Timer()
class is a singleton, which means that there can only be one instance of the class. This is to ensure that the same Timer()
is used for all threads and that each thread is unique.
Without Context Manager#
If you don't want to use the context manager with
statement, you can get the same result with a little more code:
Python | |
---|---|
How it appears in the terminal:
% Elapsed time: 0.12345 seconds for thread B
% Elapsed time: 6.78 seconds for thread A
Flow Diagram#
How the Timer starts and stops different threads: