Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

# multithreading for optimal use of CPU

# multithreading for optimal use of CPU
import time
import threading

def calc_square(numbers):
    print("calculate square numbers")
    for n in numbers:
        time.sleep(1) # CPU becomes idle for 1 second
        print('square:',n*n)

def calc_cube(numbers):
    print("calculate cube of numbers ")
    for n in numbers:
        time.sleep(1) # CPU becomes idle for 1 second
        print('cube:',n*n*n)

arr = [2,3,8,9]

t = time.time()

t1= threading.Thread(target=calc_square, args=(arr,))
t2= threading.Thread(target=calc_cube, args=(arr,))

t1.start()
t2.start()

t1.join()
t2.join()

print("DONE IN : ",time.time()-t)

# Multithreading allows the execution of multiple parts of a program at the same time. This can be crucial at times when multiple actions that happen simultaneously needs to be handled. Else, they can be used to execute another piece of code(function) while the CPU is idle.
Comment

PREVIOUS NEXT
Code Example
Python :: Find number of triangles that can be made by given sides of triangle 
Python :: r is.na pandas 
Python :: scipy z value to pvalue 
Python :: # convert a string to words 
Python :: clear terminal anaconda 
Python :: pairplot hide original legend 
Python :: pandas dataframe how to store 
Python :: python bitcoin prices 
Python :: create view django not saving image 
Python :: saving a dta file 
Python :: extracting bounding box from xml file python 
Python :: modern ui python 
Python :: link prettify in beautifulsoup 
Python :: Math Module atan() Function in python 
Python :: enumerate zip together 
Python :: NO OF CLASSES IN PAVIA UNIV DATASET 
Python :: pandas version for python 3.9 
Python :: how to add item to a list in pithon 
Python :: transfer learning in python with custom dataset 
Python :: list expression inside bracket python 
Python :: Python NumPy copyto function example copy elements from a source array to a destination array. 
Python :: make python standalone 
Python :: Python NumPy block Function Example by using np.eye function 
Python :: Python NumPy insert Function Example Using insertion at different points 
Python :: pass dictionary to random forest regressor 
Python :: what are while loops in python 
Python :: NumPy right_shift Syntax 
Python :: numpy image processing 
Python :: config.ini list not string 
Python :: knn compute_distances_two_loop 
ADD CONTENT
Topic
Content
Source link
Name
1+4 =