Send Close Add comments: (status displays here)
Got it!  This site "robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: Code timing
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: Code timing
Whenever improving code, it can be useful to time critical sections of code to see how much time code actually requires.

This page looks at some Python features for timing code.

2. Timer
The Python timeit module has a class called Timer that can be used to time code.

Here is an example of timing string concatenation using just concatenation and then with list append and join.

Often, one would include a base case that has all the code that does not do anything so that, if that time is significant, it can be accounted for in analysis.

In this case, the pass statement is used for the empty loop body so that the function call and the loop (doing nothing) are timed.

Here is the Python code [#1]


3. Timing results
From the timing results, it can be seen that for a large number of concatenations, list append and then join is much faster.

This conclusion applies to in many other languages that handle strings in a similar manner (JavaScript, Java, Lua, etc.). Here is the output of the Python code.


4. Strings
Strings in Python are immutable. That is, once created, they cannot be changed.

However, a Python string variable is a class with a value. That value can be replaced with a new value, but the underlying string cannot be changed.


5. End of page

by RS  admin@robinsnyder.com : 1024 x 640