Often on forums and chats there are hot disputes about which version of several code is performed faster. Fortunately, Python has a Timeit module that allows you to quickly measure and compare code performance.
๐ Example: We will determine which code is faster:
>>> Timeit.timeit ('"-". Join (str (n) for n in range (100))', number = 10000)
0.23387694358825684
>>> Timeit.timeit ('"-". Join ([str (n) for n in range (100)])', number = 10,000)
0.20793890953063965
>>> Timeit.timeit ('"-". Join (MAP (str, range (100)))', Number = 10000)
0.2012779712677002
It turned out that the third.
If you need to contact variables or modules from the global visibility zone in the test piece of code, it is convenient to use the Globals parameter and assign its Globals () function results.
>>> Timeit.timeit ('Math.cos (My_Cost), Globals = Globals ())
0.12635547306854278
You can also transmit the name of the function (without parameters) to Timeit:
>>> Def Foo (): "-". Join (Map (str, range (1000)))
>>> Timeit.timeit (Foo, Number = 1000)
๐ Timeit can be called from the terminal:
Python -m Timeit -s "From Math Import SQRT" -n 10,000 "x = sQRT (25)"
After the key -s there is a string of initialization; It will be completed once. The key -n will set the number of test iterations (it is recommended at least 1000).
⚠️ Remember that test results may vary depending on your computer, OS, versions of Python, phase of the moon and much more. We also advise you not to get carried away with excessive optimization to the detriment of code readability.
We wish you productive programming!
#machinelearning #artificialintelligence #ai #datascience #programming #Deechnology #Deeuplearning #bigData #bigdata