Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Sleep in Python
3.
Controlling Sleep Time
4.
Sleep
5.
Wait
6.
Busy Waiting
7.
Implementing Timeouts using Sleep
8.
Implementing Delays using Sleep
9.
Using Sleep to avoid Deadlocks
10.
Frequently Asked Questions 
10.1.
What is the syntax of the sleep function in Python? 
10.2.
How does the sleep function work in Python? 
10.3.
What is the parameter of the sleep function in Python? 
10.4.
Can we use a float value as a parameter in Python's sleep function? 
11.
Conclusion 
Last Updated: Mar 27, 2024
Easy

What is the Sleeping Time of Python

Author Abhay Rathi
1 upvote

Introduction

Hello Ninjas! In Python, the sleeping time function allows us to pause the execution of our program for a specified amount of time. This could be useful in various situations like simulating real-world delays, coordinating with other programs or systems or simply adding a pause to control the flow of our code. Let’s dive in!

sleep time of python

Sleep in Python

In Python, the “sleep” function is used to pause the execution of a program for a specified amount of time. The function is part of the “time” module, which is a built-in module in Python

That provides various time-related functions.

Below is the syntax of the “sleep” function.

import time
  
print(time.ctime())
time.sleep(5)   
print(time.ctime())  


Output:

Output for sleep in python


During this 5-second pause, the program will not execute any further code, effectively “sleeping” for 5 seconds.

Note: It's important to note that the "sleep" function is a blocking function, which means it prevents any other code from running during the pause. This might be an issue if your program has to be responsive during the pause. In certain circumstances, you should think about adopting asynchronous programming approaches instead.

Learn more, Fibonacci Series in Python, and Convert String to List Python

Controlling Sleep Time

We can use time module to control sleep time in python. To use the “time” module, you first need to import it into your code. You can do this using the below code:

import time  

 

Once you’ve imported the time module, you can use its various functions to control sleep time in your programs.

The most common function in the time module for controlling sleep time is the “sleep()” function. HTis function takes a single argument, which is the number of seconds that you want your code to pause for:

Here's a sample code to do so:

import time

print("Starting implementation...")
time.sleep(10)
print("10 seconds have passed.")


Output:

Output for the sample code

In the above example the code will first print “Starting implementation...” then pause for 10 seconds using the ‘sleep()’ function, before finally printing “10 seconds have passed”.

The time() method in the time module may also be used to determine the current time in seconds since the Epoch (January 1, 1970).

import time

start_time = time.time()
print("Starting implementation... ")
time.sleep(5)
end_time = time.time()
print("Program finished in ", end_time - start_time, "seconds.")


Output:

output using time module to calculate epoch time

In the above example, we’re using the “time()” function to record the start time of the code, and then again after the ‘sleep()’ function has completed to calculate how long the program took to run.

The time module contains a range of useful methods for working with dates, times, and durations in addition to the sleep() and time() operations. You may improve the accuracy and control of your Python programs by learning how to utilise these functions properly.

Let's see the difference between Sleep, Wait and Busy Waiting Functions In Python.

Sleep

  1. The time.sleep() method is used to suspend program execution for a set amount of seconds.
     
  2. As an input, the function accepts a floating-point value denoting the number of seconds to halt the program.
     
  3. The function is blocking, which means that the program will not continue to execute until the stated time has passed.
     
  4. The function is part of the time module in Python.


Here’s an example of Sleep:

import time

print("Start of program")
time.sleep(5)
print("End of program")


Output:

Output for example code of sleep

Wait

  1. The threading.Event().Wait() method is used to suspend the execution of a thread until a certain condition is met.
     
  2. The function creates an ‘Event’ object, which can be used to signal when a condition is met.
     
  3. The function is non-blocking, which means that the programme will continue to execute until the stated time has passed.
     
  4. The function is part of the ‘threading’ module in Python.


Here's an example of wait:

import threading

event = threading.Event()

def do_something():
    print("Ninja is running")
    event.set()

print("Ninja stands up")
t = threading.Thread(target=do_something)
t.start()
event.wait()
print("Ninja sits down")


Output:

In this example, the code creates and Event object and passes it to a new thread. The new thread will print “Ninja is running” and then set the event. The main thread would wait for the event to be set before printing “Ninja sits down”.

Output for implementation of wait

Busy Waiting

  1. Busy waiting is a technique where a program repeatedly checks a condition until it becomes true. 
     
  2. The technique is implemented using a loop, where the program repeatedly checks the condition.
     
  3. The technique can be resource-intensive and should be used sparingly.


Here's a code using Busy Waiting technique:

import time

def is_condition_met():
    return True  # Replace with your condition
print("Start of program")
while not is_condition_met():
    time.sleep(10)
print("End of program")


Output:

In the above example, the code defines a function ‘is_condtion_met()’ that returns the boolean value The main thread will repeatedly call this function and sleep for 10 seconds until the condition is met.

ouput for busy-waiting technique

Implementing Timeouts using Sleep

To implement Timeouts you may use a combination of time.sleep() and a loop to determine whether a certain condition has been satisfied within a given time limit. Lets say you want to wait for 30 seconds for a user input, you may use:

import time

timeout = 30  # In seconds
start_time = time.time()

print("Enter your Age:")
while (time.time() - start_time) < timeout:
    name = input()
    if name:
        break
    else:
        print("Please enter your age:")
else:
    print("Sorry, time is up!")


Outputs:

In the above example, the code will ask the user to enter their age and wait for input using a while loop. If the user enters an age within the time limit of 30 seconds, the loop will break, and the program will continue. Else the loop will exit and print, "Sorry, time is up!".

User enters the age in the stipulated time:

time out scenario 1 output

When user fails to enter the age within 30 seconds:

time out scenario output 2

Implementing Delays using Sleep

You may use the time.sleep() method to halt the program for a defined number of seconds to add a delay to your code. For instance, if you wish to halt the programme for 2 seconds, use:

import time

print("Start of program")
time.sleep(2)
print("End of program")

Ouput:

output for implementing delays using sleep

Using Sleep to avoid Deadlocks

This code demonstrates how to use a lock object to avoid resource contention and deadlock in a multithreaded and multiprocessing program. The code creates a lock object using the threading.Lock() function and passes it as an argument to a work function that runs indefinitely in a thread and a process.

'''
    Using sleep in multithreaded and multiprocessing 
    programs to avoid resource contention and deadlock
'''

# Import the threading module for creating threads
import threading 

# Import the multiprocessing module for creating processes
import multiprocessing  

# Import the time module for using sleep() function
import time  

# Thread worker function
def worker_thread(lock):
    print("Worker thread starts")
    
    # Repeat indefinitely
    while True:  
        # Try to acquire lock, timeout after 1 second
        acquired = lock.acquire(timeout=1)
        
        # If lock was acquired
        if acquired:  
            print("Worker thread acquired lock")
            
            # Do some work (sleep for 1 second)
            time.sleep(1)  
            
            # Release lock
            lock.release() 
            
            print("Worker thread released lock")

# Process worker function
def worker_process(lock):
    print("Worker process starts")
    
    # Repeat indefinitely
    while True:  
        # Try to acquire lock, timeout after 1 second
        acquired = lock.acquire(timeout=1)
        
        # If lock was acquired
        if acquired:  
            print("Worker process acquired lock")
            
            # Do some work (sleep for 1 second)
            time.sleep(1)  
            
            # Release lock
            lock.release()  
            
            print("Worker process released lock")

def main():
    # Create a lock object
    lock = threading.Lock()  
    
    # Create a thread with the worker_thread function and lock as arguments
    thread = threading.Thread(target=worker_thread, args=(lock,))
    
    # start the thread
    thread.start()  
    
    # Create a process with the worker_process function and lock as arguments
    process = multiprocessing.Process(target=worker_process, args=(lock,))
    
    # Start the process
    process.start()  
    
    # Wait for 10 seconds
    time.sleep(10) 
    
    # Stop the thread
    thread.stop() 
    
    # Terminate the process
    process.terminate()  

if __name__ == "__main__":
    # Run the main function
    main()


The worker_thread() and worker_process() functions are the worker functions that attempt to acquire the lock and release it after sleeping for 1 second. If another thread or process already acquires the lock, they wait for a maximum of 1 second before timing out and trying again.

The main() function creates a thread and a process with the worker_thread() and worker_process() functions and starts them. It sleeps for 10 seconds before stopping the thread and terminating the process.

Output:

Ouput for using sleep to avoid deadlock


The worker thread and process alternate acquiring and releasing the lock every second, with each thread waiting for the other to release the lock before attempting to acquire it. This demonstrates how a lock can be used to prevent race conditions and ensure mutual exclusion in a multithreaded and multiprocessing program.

Frequently Asked Questions 

What is the syntax of the sleep function in Python? 

The syntax is : time.sleep(seconds) where seconds is the number of seconds to pause the program's execution.

How does the sleep function work in Python? 

Internally, the sleep() method communicates with the operating system's scheduler to halt programme execution. During the sleep phase, the programme relinquishes CPU time, allowing the system to schedule other activities or processes. When the specified sleep duration expires, the programme wakes up and resumes execution where it left off.

What is the parameter of the sleep function in Python? 

The parameter of the sleep () function in Python is a floating-point number that represents the duration of time, in seconds, for which the program will pause its execution. The value of this parameter should be a positive number, or else a ValueError exception will be raised.

Can we use a float value as a parameter in Python's sleep function? 

Yes, we can use a float value as a parameter in Python's sleep () function. The sleep() function expects a floating-point number as the input, representing the number of seconds to pause the program's execution. The floating-point number can be a fraction, such as 0.65, which would pause the program's execution for half a second.

Conclusion 

This article discussed the sleeping time of Python. Python's sleep() function is a powerful tool that allows programmers to impose delays and halt the execution of their programs for a set amount of time. To learn more about Python.

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Happy Coding!

Live masterclass