{"id":3465,"date":"2020-02-19T21:46:01","date_gmt":"2020-02-19T21:46:01","guid":{"rendered":"https:\/\/www.askpython.com\/?p=3465"},"modified":"2022-08-06T13:12:01","modified_gmt":"2022-08-06T13:12:01","slug":"python-timeit-module","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-timeit-module","title":{"rendered":"Python timeit Module"},"content":{"rendered":"\n<p>The Python <strong>timeit<\/strong> <a href=\"https:\/\/www.askpython.com\/python-modules\/python-modules\" class=\"rank-math-link\">module<\/a> is a simple interface to quickly measure the execution time for small blocks of code.<\/p>\n\n\n\n<p>When you are creating an application, you may wonder how this block of code will perform and would want to test it under different scenarios.<\/p>\n\n\n\n<p>For this, the <code>timeit<\/code> module provides a very simple solution to this problem. Let&#8217;s look at how we can use this to time our code snippets!<\/p>\n\n\n\n<p>We shall be looking at both the <strong>Command Line Interface<\/strong> and a <strong>Callable interface<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python timeit &#8211; Command Line Interface<\/h2>\n\n\n\n<p>The command-line interface is very similar to that of running a Python program.<\/p>\n\n\n\n<p>You need to import the external module <code>timeit<\/code> using the -m option and apply it to your code.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npython -m timeit &#039;print(&quot;Hello from AskPython&quot;)&#039;\n<\/pre><\/div>\n\n\n<p>This will run the snippet, passed as a string, using <code>timeit<\/code>.<\/p>\n\n\n\n<p>By default, this will run the code 1 million times on Linux and 20 million times on Windows, and measure the best time among those values. The below outputs are from my Linux system.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"581\" height=\"128\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_cli_default.png\" alt=\"Python Timeit Cli Default\" class=\"wp-image-3466\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_cli_default.png 581w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_cli_default-300x66.png 300w\" sizes=\"auto, (max-width: 581px) 100vw, 581px\" \/><\/figure><\/div>\n\n\n\n<p>Note that if you already have a for loop in your snippet, the module will ensure that the total number of iterations is close to 1 million, so your entire loop will not run for 1 million times! <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"652\" height=\"75\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_example_2.png\" alt=\"Python Timeit Example 2\" class=\"wp-image-3471\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_example_2.png 652w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_example_2-300x35.png 300w\" sizes=\"auto, (max-width: 652px) 100vw, 652px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Python timeit &#8211; Python Interface<\/h2>\n\n\n\n<p>We can also use <code>timeit<\/code> via the Python interpreter, and import it using:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport timeit\n<\/pre><\/div>\n\n\n<p>To find the execution time, pass the code as a string to <code>timeit.timeit()<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nexecution_time = timeit.timeit(code, number)\n<\/pre><\/div>\n\n\n<p>We can control the number of iterations using the <code>number<\/code> parameter.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; timeit.timeit(&#039;&quot;-&quot;.join(str(n) for n in range(100))&#039;, number=10000)\n0.19053685299877543\n&gt;&gt;&gt; timeit.timeit(&#039;&quot;-&quot;.join(&#x5B;str(n) for n in range(100)])&#039;, number=10000)\n0.172546762998536\n&gt;&gt;&gt; timeit.timeit(&#039;&quot;-&quot;.join(map(str, range(100)))&#039;, number=10000)\n0.13625987299747067\n&gt;&gt;&gt; \n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Using the timeit Module<\/h2>\n\n\n\n<p>Let&#8217;s now look at how we can use <code>timeit<\/code> to time a snippet, inside our program.<\/p>\n\n\n\n<p>But before that, you may be wondering about something. What if your code required some previous setup to be done? And if you need to import certain modules too?<\/p>\n\n\n\n<p>Well, the solution to this problem is to use a <strong>setup<\/strong> code block, which will do all the necessary work in setting up all required modules and variables.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nsetup_code = &quot;import math&quot;\n<\/pre><\/div>\n\n\n<p>Writing a setup block is very simple. You simply write whatever code you need, and pass it as a string, into a variable.<\/p>\n\n\n\n<p>After this, you can write your main code block and pass it to <code>timeit.timeit()<\/code>, using the <code>setup<\/code> and <code>stmt<\/code> parameters.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nexecution_time = timeit.timeit(setup = setup_code, stmt = main_block, number = 100)\n<\/pre><\/div>\n\n\n<p><code>timeit<\/code> will ensure that the setup is done before your main loop is measured, so it is only executed once!<\/p>\n\n\n\n<p>Let&#8217;s quickly look at an example now.<\/p>\n\n\n\n<p>This code tries to get all sub-arrays from the starting element of a <strong>numpy<\/strong> array. Notice that the setup block is run only once. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport timeit\n\n# Setup is run only once\nsetup_code = &#039;&#039;&#039;\nimport numpy as np\na = np.arange(0, 1000)\nprint(a.shape)\ndef print_subarrays(a):\n    op = &#x5B;]\n    for i in range(a.shape&#x5B;0]):\n        op.append(a&#x5B;:i])\n&#039;&#039;&#039;\n\nmain_block = &#039;&#039;&#039;\nprint_subarrays(a)\n&#039;&#039;&#039;\n\n# Main Block is run 1000 times\nprint(&#039;Best execution Time among 1000 iterations:&#039;, timeit.timeit(setup=setup_code, stmt=main_block, number=1000))\n\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n(1000,)\nBest execution Time among 1000 iterations: 0.3830194959991786\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Compare the Performance of Code Blocks<\/h2>\n\n\n\n<p>We can easily compare the performance of multiple blocks of code using <code>timeit<\/code>.<\/p>\n\n\n\n<p>We will use a timer for this purpose, using <code>timeit.default_timer()<\/code>.<\/p>\n\n\n\n<p>The time taken for a code block will be the current time minus the initial time taken as reference, which you can pass through variables.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport timeit\n\nstart_time = timeit.default_timer()\nfunction_1()\ntime_1 = timeit.default_timer() - start_time\n\nstart_time = timeit.default_timer()\nfunction_2()\ntime_2 = timeit.default_timer() - start_time\n\nprint(&#039;Function 1 took&#039;, time_1)\nprint(&#039;Function 2 took&#039;, time_2)\n<\/pre><\/div>\n\n\n<p>Let&#8217;s test 2 functions on a numpy array <code>range()<\/code> and <code>np.arange()<\/code> and see how they compare.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport timeit\nimport numpy as np\n\ndef time_range(size):\n    for i in range(size):\n        pass\n\ndef time_arange(size):\n    np.arange(size)\n\nif __name__ == &#039;__main__&#039;:\n    # For smaller arrays\n    print(&#039;Array size: 1000&#039;)\n\n    start_time = timeit.default_timer();\n    time_range(1000)\n    range_time_1 = timeit.default_timer() - start_time\n\n    start_time = timeit.default_timer();\n    time_arange(1000)\n    arange_time_1 = timeit.default_timer() - start_time\n\n    # For large arrays\n    print(&#039;Array size: 1000000&#039;)\n\n    start_time = timeit.default_timer();\n    time_range(1000000)\n    range_time_2 = timeit.default_timer() - start_time\n\n    start_time = timeit.default_timer();\n    time_arange(1000000)\n    arange_time_2 = timeit.default_timer() - start_time\n\n    print(f&#039;size 1000: range() took {range_time_1}&#039;)\n    print(f&#039;size 1000: arange() took {arange_time_1}&#039;)\n    print(f&#039;size 1000000: range() took {range_time_2}&#039;)\n    print(f&#039;size 1000000: arange() took {arange_time_2}&#039;)\n\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nArray size: 1000\nArray size: 1000000\nsize 1000: range() took 2.2970001737121493e-05\nsize 1000: arange() took 8.393999451072887e-06\nsize 1000000: range() took 0.02567379199899733\nsize 1000000: arange() took 0.0031752489994687494\n<\/pre><\/div>\n\n\n<p>Thus, we could easily use <code>timeit<\/code> to compare the performance of different functions.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Time a Particular Function<\/h2>\n\n\n\n<p>We can also only time the performance of a specific function in a script, without running the other code blocks.<\/p>\n\n\n\n<p>If the earlier file was called <strong>numpy_compare.py<\/strong>, we can find the execution time using the below invocation:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython -m timeit -s &#039;import numpy_compare&#039; &#039;numpy_compare.time_range(1000)&#039;\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"844\" height=\"69\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_test_on_function.png\" alt=\"Python Timeit Test On Function\" class=\"wp-image-3483\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_test_on_function.png 844w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_test_on_function-300x25.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/python_timeit_test_on_function-768x63.png 768w\" sizes=\"auto, (max-width: 844px) 100vw, 844px\" \/><figcaption>Python Timeit Test On Function<\/figcaption><\/figure><\/div>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Hopefully, you&#8217;re now familiar with the basics of this module, so it&#8217;s time for you to start using it and increase your productivity!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a class=\"rank-math-link\" href=\"https:\/\/docs.python.org\/3\/library\/timeit.html\" target=\"_blank\" rel=\"noopener\">Python timeit module Documentation<\/a><\/li><li><a class=\"rank-math-link rank-math-link\" href=\"https:\/\/stackoverflow.com\/questions\/8220801\/how-to-use-timeit-module\/29512249\" target=\"_blank\" rel=\"noopener\">StackOverflow Question on timeit module<\/a><\/li><li>JournalDev article on Python timeit module<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>The Python timeit module is a simple interface to quickly measure the execution time for small blocks of code. When you are creating an application, you may wonder how this block of code will perform and would want to test it under different scenarios. For this, the timeit module provides a very simple solution to [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":3501,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-3465","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3465","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=3465"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3465\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/3501"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=3465"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=3465"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=3465"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}