{"id":1551,"date":"2019-07-05T20:34:23","date_gmt":"2019-07-05T20:34:23","guid":{"rendered":"http:\/\/www.afternerd.com\/blog\/?p=1551"},"modified":"2019-07-05T20:34:23","modified_gmt":"2019-07-05T20:34:23","slug":"python-sleep-function-explained","status":"publish","type":"post","link":"https:\/\/www.afternerd.com\/blog\/python-sleep-function-explained\/","title":{"rendered":"Python: Sleep Function Explained"},"content":{"rendered":"<p>In Python, or any other programming language, sometimes you want to add a time delay in your code before you proceed to the next section of the code.<\/p>\n<p>If this is what you want to do, then you should use the <strong>sleep<\/strong> function from the <a href=\"https:\/\/docs.python.org\/3\/library\/time.html\" target=\"_blank\" rel=\"noopener noreferrer\">time<\/a> module.<\/p>\n<p>First, I will start by discussing how to use Python&#8217;s <strong>sleep<\/strong> function. After that I will talk more about some frequently asked questions and how the <strong>sleep<\/strong> function is actually implemented under the hood.<\/p>\n<h2>Sleep function<\/h2>\n<p>Like I mentioned, Sleep is a Python built-in function in the <strong>time<\/strong> module.<\/p>\n<p>So in order to use <strong>sleep<\/strong>, you will need to import the <strong>time<\/strong> module first.<\/p>\n<p>sleep takes only one argument which is the period of time in seconds that you want to sleep for.<\/p>\n<p>Using the <strong>sleep<\/strong> function in <strong>Python 2<\/strong> and <strong>Python 3<\/strong> is exactly the same, so you won&#8217;t need to worry about which version of Python your code is running on.<\/p>\n<p>It is really very simple and straight-forward. Let&#8217;s walk through some examples.<\/p>\n<h3>Python 2<\/h3>\n<p>Let&#8217;s say you want to use <strong>sleep<\/strong> to add a 10-second delay.<\/p>\n<p>In the following example, I print out the elapsed time between <em>invoking<\/em> the sleep function and after it <em>returns<\/em>.<\/p>\n<pre class=\"prettyprint\"><code>import time\r\n\r\n# record start time\r\nstart_time = time.time()\r\n# sleep for 10 seconds\r\ntime.sleep(10)\r\n# print elapsed time\r\nelapsed_time = time.time() - start_time\r\nprint(elapsed_time)\r\n\r\n# output: 10.000149965286255<\/code><\/pre>\n<p>As you can see, the elapsed time is very close to 10 seconds which is what we expect.<\/p>\n<h3>Python 3<\/h3>\n<p>No changes in Python 3.<\/p>\n<p>You can use the <span class=\"symbol\">sleep<\/span> function in Python 2 exactly as you do in Python 2.<\/p>\n<h2>Frequently Asked Questions<\/h2>\n<h3>Q: How to use the sleep function to sleep for a time period that is less than a second, for example milliseconds or microseconds?<\/h3>\n<p>Great question.<\/p>\n<p>The sleep function actually takes a floating point number as an argument, not an integer.<\/p>\n<p>And that means, you can pass any fraction of a second as an argument.<\/p>\n<p>For example:<\/p>\n<pre class=\"prettyprint\"><code>import time\r\n\r\n# sleep for half a second\r\ntime.sleep(0.5)\r\n\r\n# sleep for 1 millisecond\r\ntime.sleep(1 * 10**(-3))\r\n\r\n# sleep for 1 microsecond\r\ntime.sleep(1 * 10**(-6))<\/code><\/pre>\n<h3>Q: How to use the sleep function to sleep until a specific time?<\/h3>\n<p>This is a very common question.<\/p>\n<p>Depending on what you are trying to do, there are two different ways to achieve this.<\/p>\n<p>The straight-forward way is to precompute the delay (in seconds) until that specific time before you call the sleep function.<\/p>\n<p>Another way is to use the <a href=\"https:\/\/docs.python.org\/2\/library\/threading.html#threading.Event.wait\" target=\"_blank\" rel=\"noopener noreferrer\">event.wait<\/a> function from the <strong>event<\/strong> module.<\/p>\n<p>If what you are trying to do is to block a thread until a <strong>condition<\/strong> happens, it is much better to use <strong><span class=\"symbol\">wait()<\/span><\/strong>.<\/p>\n<h3>Q: [Advanced] How is sleep actually implemented?<\/h3>\n<p>This is a fantastic question.<\/p>\n<p><strong>sleep<\/strong> is not actually implemented by Python.<\/p>\n<p>Well, it is, but it is simply a wrapper around something else that is implemented by the Operating System.<\/p>\n<p>All Operating Systems have a <span class=\"symbol\">Sleep()<\/span> system call.<\/p>\n<p>If you don&#8217;t know what a <a href=\"https:\/\/www.geeksforgeeks.org\/operating-system-introduction-system-call\/\" target=\"_blank\" rel=\"noopener noreferrer\">System Call<\/a> is, then you should!<\/p>\n<p>here is <a href=\"https:\/\/amzn.to\/2S0QBeF\" target=\"_blank\" rel=\"noopener noreferrer\">the book that I recommend for learning about Operating Systems concepts.<\/a><\/p>\n<p>But either way, you can think of a System Call as an API or an interface that the OS provides for user-space programs to interact with the OS.<\/p>\n<p><em>So what does an OS do when it receives a Sleep System Call?<\/em><\/p>\n<p>Basically what the OS will do is that it will suspend the process (your program) from being scheduled on the CPU for the time period that you specified.<\/p>\n<p>Notice that this is completely different from adding delay using a dummy for loop that does nothing (which is something you should NEVER do).<\/p>\n<p>In the case of a dummy for loop, your process is actually still <em>running<\/em> on the CPU.<\/p>\n<p>But in the case of <strong>Sleep()<\/strong>, your process will be effectively <em>dormant<\/em> for a while until the OS starts scheduling it again on the CPU.<\/p>\n<h3>Learning Python?<\/h3>\n<p>Check out <a href=\"https:\/\/courses.afternerd.com\/\">the Courses section!<\/a><\/p>\n\n<h2>Featured Posts<\/h2>\n<ul>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-python\/\">The Python Learning Path (From Beginner to Mastery)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-computer-science\/\">Learn Computer Science (From Zero to Hero)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/coding-interview\/\">Coding Interview Preparation Guide<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/stock-investing-for-beginners\/\">The Programmer&#8217;s Guide to Stock Market Investing<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/start-programming-blog\/\">How to Start Your Programming Blog?<\/a><\/li>\n<\/ul>\n<div class=\"after-post-box\">\n<h2>Are you Beginning your Programming Career?<\/h2>\n<h3>I provide my best content for beginners in the newsletter.<\/h3>\n<ul>\n<li>Python tips for beginners, intermediate, and advanced levels.<\/li>\n<li>CS Career tips and advice.<\/li>\n<li>Special discounts on my premium courses when they launch.<\/li>\n<\/ul>\n<p>And so much more&#8230;<\/p>\n<h3>Subscribe now. It&#8217;s Free.<\/h3>\n<p><script type=\"text\/javascript\" src=\"\/\/mautic.afternerd.com\/form\/generate.js?id=2\"><\/script><\/p>\n<\/div>\n\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":1566,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[13],"yst_prominent_words":[1373,1383,1366,160,1391,1393,1371,52,53,158,149,150,1363,1390,1392,1370,1376,295,1364,1382],"_links":{"self":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/1551"}],"collection":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/comments?post=1551"}],"version-history":[{"count":7,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/1551\/revisions"}],"predecessor-version":[{"id":1590,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/1551\/revisions\/1590"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media\/1566"}],"wp:attachment":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media?parent=1551"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/categories?post=1551"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/tags?post=1551"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=1551"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}