Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
44 views
21 pages
Utkarsh Jupiter
Parallel computing
Uploaded by
kumshubham9870
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save utkarsh jupiter For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
44 views
21 pages
Utkarsh Jupiter
Parallel computing
Uploaded by
kumshubham9870
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save utkarsh jupiter For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save utkarsh jupiter For Later
You are on page 1
/ 21
Search
Fullscreen
+ LAB-1(GDrive Mount and dataset manipulation) 1 from google.colab Inport drive 2 drive.nount(" /content/drive") Mounted at /content/érive 4 nmport pandas as pé 2 data ~ pd.read_csv(“/content/drive/MyOrive/PC LAB/Copy of span_han_dataset.csv - span_ham_éataset - Copy of spam_han date 53 print (dara) Usnaned: @ 2abel text \ 605 han Subject: enon methanol ; eter # : 98292\nth... 2349 han Subject: hpl now for january 9 , 2002\n( see a... 3624 han Subject neon retreat\nho ho no’, we "Fe arou... 4685. span Subject: photoshop , windows , office . cheap ... 2030 hon Subject: re : indian springs\ntnis deal is to... 1518 han Subject put the 10 on the Ft\nthe transport v.11 498 han Subject: 3/4 / 2080 and following nons\nhpl 2833 hon Subject: calpine dasly gas fominatien\n>\n>\nj..- 1409 han Subject! industrial worksheets for august 2000 4807 span Subject: inportant online banking alere\ndear 2 tan Nan 2 tan NaN sue MaN NaN [5171 rons x 6 colunns! 1 data.head() nna label text text.i text.2 text.3 Subject: enron methanol; meter # ° 605 ham nal meter 0 NaN NaN 4 2349 ham Subject: nplnom for january 9, 200Tin see a 0 NBN NaN 2 3624 ham Subject: neon retreatinhe ho ho, wore arou 0 NaN NaN 3 4085 spam Subject: photoshop , windows , office. cheap 1 NaN NaN 1 data.tail() Unnaned “abel text text.i text.2 text.3 st 1518 pam SeieeEPuthe TBonthefietranseot gay Nan sis? tos ham Subject: 342000 and folowing aN NaN nomial sie 2909 ham Subject caine 6aly 928g Nany NaN nominalonin>\n>\91 mport nunpy as np 2 datael = np.array((*U's TK, 3 5_no = pd.Series(datael) 4 print(s_no) soHD ° a 2 a 4 5 6 Geyper object + LAB-2(Covid 19 Dataset Manipulation) 1 datad ~ pd.read_csv("/content/drive/MyDrive/PC LAB/Copy of Covid 19 dataset - covid_19_clean_conplete.csv") 2 print (data) Province/State Country/Region tat Long \ ° NaN ‘Mghanistan 33.000000 65.000000 a Nan ‘Albania 42,353300 20.168300 2 Naw Algeria 28.033900 "1.659600 4 Nan Bngola -12.202700 17.873900 24361. saint Pierre and Miquelon France 46.885268 -56,315900 24363 Now Mestern Sahara 24.215500 -12, 885800 20364 NaN S20 Tone and Principe 9.286369 6.613081 gate Confirmed peaths Recovered 2 122/20 ee ° 1 1/22/20 e 8 ® 2 ni e 8 @ 3 22/20 e 8 e 4 ne e 8 ° 2ide1 4/23/20 18 @ 24362 4/23/20 se e 24363 4/23/20 6 8 5 2a364 4/23/20 a8 e 24365, 4/23/20 1 8 ° [24366 rows x 8 columns] 4 len(dsta2) 24266 1 data2. head) 4 dataz.tatl() 1 type(data2) ppandas.core.frane.Datafrane 1 dataz[a:s] 1 confirned_cases = data2.groupby(‘Date' )['ConFirmed"].sum() .reset_index()1 print(confirmed_cases) Date Confirmed 8 22/20 555 11/23/28 554 2/2/20 941 3 17sje1a8 4 26788 Be 4/5/28 200882 94/6/28 21129 98 4/7/28 1396090 92 4/8/28 aa79e02 92 4/9/28 1568276 [93 rows x 2 coluens] + LAB-3(Colab specifications) 4 Amport multiprocessing as ep 2 print(Nunber of processors : ",ap.epu_count()) 4 import platform 5 ay_systen = platform.unare() 6 print(F*systen: {ey_systen.systen}") 7 print(F*Mode Nane: (my_systen.nede}") 8 print(f*Release: (ny_syster.release}") 9 print(f"version: (ny_syster.version}") 28 print(Fttachine: {ny_syster.sachine}") 31 print( "Processor: {ny _systen.processor)") Number of processors : 2 system: Linux Node Nane: S6d9bca93454 Release: 5.15.220+ Version: #1 SMP Wed Aug 39 11:19:59 UTC 2023 Machine: x86_64 LAB-4(Sequential and Parallel Execution(using Pool function) to calculate square of a number) + Sequential execution 1 anport tine 2 from tineit inport default_tiner as tier 3 # Function to calculate the square of 9 number 4 dof calculate_square(nunber): 5 thne,sleep(@.e4) return mupber * nunber Sf pane unbers [12.3.4 5, 6) 7% 8 9, 10] f calculate squares sequentially 6 a 2 1 starten = tiner() 2 4 resultei = [calculate_square(nunber) for nusber An numbers] 6 endo = timer()-startor18 print("squares sequentially:", resultet) 29 print("Sequertial execution tine:",end®1, seconds") Squares sequentially: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100) Sequential execution tine: 6.002353sSe0e004347 seconds Parallel Execution 4 Anport multiprocessing 2 import tine 3 from tinelt Leport defaul 4 5 # Function to calculate the square of 2 nunber 6 dof calculate_square(nunber): mer a5 timer 7 tine. sleep(@.04) 8 return nurber * nunber 20 4 _nane__ == *_pain_’ si “hunbers = (2) 2, 3,4 5, 6) 7, 8, 9, 20) 23. steree2 ~ ciner() 25 # Create a Pool with the desired number of worker processes 26 pool = sultiprocessing.Pool (processes=8) 28 Calculate squares in parallel 39 resulte2 ~ pool.nap(caiculate_square, numbers) 21 pool. close() 22 pool. joint) 2 24 endo2 = tiner()-startoz 25 25 —_print("squares in parallel:*, resulte2) 27 print(*Parallel processing tine:", end®2, seconds") Squares in parallel: [1, 4, 9, 16, 25, 36, 49, 64, 81, 180] Parallel processing tine: @.16893749/90090124" seconds| Graph 1 tnport natplotiib.pyplot as pit 2 Fig = ple. figure) 3b [°Sequential", "arate (P001)") exe tine = [endo erd62) 5 plesbar(tyexe-tine, color ={'areen',orange'T) & pltorlabel(-biFferent functions") > pltsylabel(-Tine Takes") @ —ple-titie(*Tine taken by Sequential and Pool Process”) 9 ple.show)Time taken by Sequential and Pool Process 040 035 030 025, 020 > LAB-5(Speedup of Sequential and Parallel with Graph) | > Speedup Calculation “Time Taken 1 inport tine 2 from tineit inport default_timer as tiner 3 From multiprocessing import Pool, cpu_count 5 def power, 1m): 6 7 tine.steep(a) a 20 22 def nain() 24 start = timer) 35 36 print(F"starting conputations on (cpu_count()} cores") 27 values = [3,5,7,2,6,3,2,4,9] 28 values? = (7,3,5,6,4,7,6,4,2] 22 res = 1ist(eap(pouer, valuest,values2)) 21 print(res) 22. end = tiner() 23 print(#"Elapsed tine: {end - start)") 24 25 4 _nane_, 26 “nain() 2 Starting computations on 2 cores (2187, 125, 16867, 64, 1296, 2287, 64, 256, 81) Elapsed tie: 9.069567925999532 > Sequential vs Parallel Graph using matplotlib 4 Anport matplotlib.pyplot as plt 2 3 plt.title("Sequential tine Vs Parallel tine”) 4 plt.ylabel("Time in seconds") 5 plt.xlabel( "bata length") 7 date_size = (2,4,8)8 sequential_tine = [3.00,6.086, 9.009) 9 parailel_tine = [2.82,3.02,5.036] 2 314 Function to plot 2 plt.plot(dats_size, sequential_tine,label~"Sequential Tine") 13 plt.plot(data_size,parallel_tine, 1abel="Paralle} Tine") 2 354 Function to show the plot 46 plt.2egend()
Sequential time Vs Parallel time 9) — Sequential ime — Parallel Time Time in second 2 3 4 5 6 7 Data length > Speedup Graph 4 Anport matplotlib.pyplot as pit 3 plt.title("Speed Up Tine”) 4 plt.ylabel( "Tine in seconds") 5 plt.elabel( "ata length") 7 data_size » (2.4.8) 8 speedup_data = [1.48,1.98,1.788] 8 26 # Function to plot 1 plt.plot (data_size,specdup_data, label="Speed Up Tine”) 123 # function to show the plot 134 plt.tegend()
‘Speed Up Time 20) — Speed Up Time 1 ‘seconds LAB-6(Matrix Addition and Multiplication using Sequential, Pool and Process Methods with Graph of Execution time and Speedup) toy 1 Matrix Addition 2 3 4 > ° ' 6 Sequential 1 Amport multiprocessing 2 amport nunpy as op 3 import tine 4 Amport matplotlib.pyplot as plt 6 # Define a function to adé two matrices 7 def add_sacricesos(aatrixt, satrix2): 8 tine. sleep(5) n= Lengmatrixt) result = [[@ for _ in range(n)] fer for 4 in range(n) for 3 in range(n) resutt[][3] = matrbxa[i][4) + eatesxa[s7037 return result in range(n)] (6 # Define a function to add two natrices def add_natricese2(sateixt, eateix2): return [[a + for a, b in zip{rowt, rox2)] for row, row2 in zip(matrixt, matrix2)] 20 # Define a function to adé two natrices 21 def add_natriceso3(aatrixt, eatrix2, result, rox, 9) 2° for col in range(n) z result{row * n + col] = aatrixt[row]{col) + natréxz{row){col] 26 25 $f _nane_ == *_ain_” 26 “W= Ine Cinoue("Enter order of matrices :*)) # Change the value of *n* as needed 2 nateiea = np. randos.randine(2,10,s82e = (9,n)) 28 natebe2 = rp.randon.randint(a,10,size = (n.n)) 30 start time = tine.tiee() BL result ~ add patrices@i(eateixa, nated) 32 end_tine = tine.tineQ) 33 seqiential_tine = end tine - start_tine 34 print *Rescltant Matrix (Sequential) :=) 35 Enter order of ratrices :500 Resultant Matrix (Seauential)+ Pool 1 pool = multiprocessing. Po0l() 2 start_time = tine.tiee() 3 result = pool.apply(add_satricese2, angs=(natrixt, mateix2)) 4 end_tine = tine, tine() 5 pool.close() 6 pool. joint) 7 pool._tine = end tine - start_tine 8 prine(*Resvltant Matrix (Pool) :") 9 princ(pool_tise) Resultant Matrix (Pool): 11.414067268371582 + Process 1 Create a shared nenory array to store the result 2 result = multiprocessing.Array('i", * n) 4 processes = [] 5 start_time = tine.tie() 6 for row in range(n): 7 process = multiprocessing.Process(tanget=add_natricese3, args=(eatrixt, matrix2, cesult, row, n)) a processes.appens(process) 3 process.start() 20 21 for process in processes: 2 process. join() 3 34 # Conver the shared menory array to @ List of Lists 25 result_satrix = [result[isi +n] for 4 in range(@, nt 9, n)] 36 end_tine = tine.tine() 27 process tine = end tine - start_time 28 print(*Resultant Matrix (Process):") 29 prine(process_tine) Resultant Matrix (Process) 2,8318593897399902 > Line Graph-Execution time ethos = ["Seauential", "Pool", "Process] execution tines = [sequential tine, pool tine, pracess_téne) plt-Figure(Figsize-(18,2)) plt.plot(eethods, execution tines, marker="o') ple.tivle("execution Tine oF Matrix Adéition”) plt.xdabel (“Wethed") plt.ylabel(“Tine (seconés)") pltegrid() ple-show()Execution Time of Matix Addition Tt + Bar Graph - Speedup Bol mst a 14 Calculate speedup for each method 2 speedup_pool = sequential tine / pool_tine 3 speedup_process = sequential tine / process_tire 5 # Plot the speedup as a bar graph 6 eethods = ["P001", "Process"] 7 speedups = [speedup_pool, speedup_process} 8 plt.ban(nethods, speedups, color={‘biue', ‘green']) 9 plt.title( "Speedup of Matrix Addition”) 20 pltxlabel Method") 121 plt.ylabel(Speecup") 22 plt-grid() 133 plt.show() Speedup of Matrix Addition Speedup vethod 1 # Calculate speedup for each method 2 speedup_sequential = sequential tine / sequential_tine 43 speedup_pool = sequential tise 7 pool_tine 4 speedup_process = sequential tine / process tire 6 # Plot the speedup as a bar graph 7 wethods = ["Sequential”, "Pool", “Process"] 8 speedups = (speecup_sequential, speedup pool, specdup_process) 9 plt.ban(nethods, speedups, colors["red’, "blue", ‘green']) 48 plt.title("Speedup of Matrix Addition") 21 plt.xlabel ("Method") 422 plt.ylabel ("Speedup") 33 plt-gria() 4 plt.show()Speedup of Matrix Addition 7 > Matrix Multiplication > Defining functions for matrix multiplication and main function 1 import multiprocessing 2 smport nunpy as np 3 import tine 4 Anport natplotlib.pyplot 6 # Define a function to calculate a row of the resulting matrix 7 def aultiply_rox(args) as pit 8 natrixt, atrixa, row, n= ares 9 result row = np-zeros(n) 28 for sin range(n) n result_row(i] = np-sun(natrixt{row] * matrie2f:, £1) rretuen result_row 4 # Define a function to perform matrix multiplication for 2 row and coluan 35 def aultiply_rox_col(natrint, matrix2, result, row, col, n) 26 result(row][col] = sum(natrixa[rou][i] * natrix2[t]{eol] for 4 in range()) 128 # Main matrix multiplication function for a specific range of rows and colunns 29 def aultiply_range(natrixt, eatrix2, result, start_roa, end_row, n) 28 for 1 in range(start_row, end_row): a for jin range(n) 2 inuttiply row col(natrixt, matrix2, result, 4, J, n) 23 244 Define a Function to multiply two matrices 25 def aultiply natrices(natrixi, matrix2, result, row, col, a) 25 result{row)[col] = @ 27 for 4 in range(n): 28 result{row][col] += matrixt[row](4] * matrix2[4} [col] 29 38 1 _nane_ == *_pain_’ 31 “a= int(input("Enter order of matrices :")) # Change the value of ‘n’ as needed 52° aatrixt = np.randoa.randint(1,20,size = (a,n)) 33° natrix? = np.randon.randint (4,30, size = (n,n)) Enter order of matrices :490 + Sequential4 Sequential Execution start_time = tine. tiee() sequential_result = [[@ for _ in range(n)] for for 4 An range(n): for 3 in range(n): iultiply matrices(aatrixt, matrix2, sequential result, 4, 4, n) 1e = tine, tine() sequential_tine = end tine - start_tine 4 prine("Resultant matrix (Sequential):") 4 For row in sequential result: 4% print(row) prine("Sequential Execution Tine:", sequential_tine, "seconds") in range(n)] Sequential Execution Tine: 58,78011441230776 seconds > Pool 1 pool = multiprocessing. Pool(pracessessmultiprocessing-cpu_count()) # Use available CPU cores, 2 start_time = tine.tiee() 5 result = np.array(poot.map(multiply rom, [(satrixt, matrix2, 1, n) for 4 in range(n)])) 7 end_tine = tine.tine() 3 pool_tine = end tine - start tie 28 print("Mateix Multiplication Execution Tine (Po0l):", pool_tine, “seconds") Notrix Multiplication Execution Tine (Pool): 1,3108648253845215 seconds ~ Process processes = (J hnun_processes = multiprocessing.cpu_count() # Use available CPU cores chunk_size = n // nun processes start_tine + tine.tine() for & in range(nun_processes) start_row = 17 chunk size end.row = (+ 1) * chunk size 4f £ < numprocesses - 2 else n process = multiprocessing. Process (canget=nultiply range, arg processes. append(process) process.start() atric, matrbe2, result, start_row, end_rox, 9)) for process in processes: process. join() end_tine = tine.tire() process tine = end tine - start_tine pet Matrix Multiplication Execution Tine (Process):", process_tine, “seconds") Matrix multiplication execution Tae (Process): 49.377851724626634 seconds + Bar Graph- Execution time 4 eethods = ["Sequentia!", "Pool", “Process"] 2 execution tines = [st 3 plt.bar( tine, pool_tire, process tine] ines, colore["red","blue’, ‘green"]) ds, execution +4 plt-title("execution Time Matebx Mul 5 plt.xlabel(“Method") 6 plt.ylabel("Tine(in seconds)") 7 pltgrid() 8 plt.show() plication") Execution Time Matrix Multiplication 0 ” Fw i Eo » js — Sequential rol traces wetied + Bar Graph - Seepdup 1 # Calculate speedup for each nethod ime / sequential_tine tine 7 pool_tine 4 speedup_process = sequential_tine / process_tire 6 # Plot the speedup as a bar graph Y eethods = ["Sequential”, "Pool", "Process"] 2 speedup_sequential = sequential 3 speedup_pool = seque 8 speedups = [speecup_sequential, speedup_peol, speedup_process) 9 plt.ban(nethods, speedups, color=['red’, "blue", ‘green']) 26 plt.title("Speedup of Matrix addition") 21 plt.xlabel( Method") 122 plt.ylabel ("Speedup") eria() show)Speedup of Matrix Addition 40 3% LAB-7(Searching an element in a list applying Linear Search using Sequential, . Pool, Parallel and Threading Methods with Graph of Execution time and Speedup) 71 — 1 ~ Defining Searching functions and main function 1 Anport multiprocessing 2 import threading 3 import tine 4 Amport random ‘tine. sLeep(2) resuits = (7 for ites in data: $f Sten == target: results. append(iten) ‘ine. tine() execution tine = eng_tine - star return rezults, execution tine ends search worker(éata, start, end, target, results) local_results = (] for i in range(start, end): Sf data[i] == target: local_results. ppend(cata[]) results.extend(local_results) ef pool_search(target, data) start_tine = tine.tine() results = (] vith nultiprocessing.P001() a5 pool: chunk_size = len(data) // multiprocessing.cpu_count() for {in range(@, len(dats), chunk_size) pool. apply_asyne(search worker, argse(data, i, 1 + chunk size, target, results)) poal.cloze() oot. Joint) je » tine. tine() retunn results, execution tine process_search(target, data) start_time = tine. tire) results = multiprocessing.Aray('i", len(data)) processes = [] chunk_size = len(data) // aultiprocessing.cpu_count() for £ in range(®, len(data), chunk_size) process = multiprocessing. Process (canget=search worker, ar (data, 1, 1 + chunk size, target, results)) processes.appens(process) process.start() fer process in processes process. join()S1 result list ~ 13st(results) 52 end tine = tine.tine() 57 def threaded search(target, data) So results = (] Ge nun threads = threading. active_count() a G2 chunk size = Len(data) // mua_threads 8 fa threads = 11 6S for A in ranga(num_thresds) Ge thread = threading. theend(targetssearch worker, arg @ ‘hresdsappend( tread) thread. start) & 70 for thread in threads n ‘hread. joint) 13 end.tine = tine.tine) 75 return results, execution tine 77:36 pane, o= “ain 78 “p= 10600000" change the nunber of elements a5 needed 79 target_element = randon.randint(@, n)” # Random element to search for 86 data = {randon.randine(O, n) for in range(n)] # Generate randon data + Sequential 1 Seqventiat Search 2 Sequetial_results, sequential tine = sequential, searen(target_elenent, data) 4 —_print(*Sequentiol Execution Time:“, sequential tine, “seconds") & calculate speedup 7 Sequential_speedup = sequential_tine / sequential tire 8 print ("Speedup(Sequential):", sequential_speedup) Spoosup(sequentioy. 1-8 > Pool 1 # Pool Search 2 pool.resitts, poot_tine = pool_search(carget_elesent, data} 3 4 princ(*Poot Execution Tine:*, pool_tine, “seconds") 5 © catcutate Speedup 7 pool_speedup = sequential tine / pool_tine 8 —-prins("Speedop( Pool)", poe] speedup) Pool Execution Tine: 4,800148010253506 seconds Speedup(Pool): @.9184ss59s8672848 + Process (data, 1 * chunk size, (1 +1) * chunk size, target, results1 # Process Search 2 process results, process time = process_search(target_clement, data) 4 print("Process Execution Time:", process tine, "seconds") 6 — # Calculate Speedup 7 process_speedup = sequential_tive / process tine 3 print("Speedup(Process):", process_ speedup) Traceback (Rost recent call last) File "/usr/1ib/pyten3.2e/multiprocessing/process.py", Line 314, in _bootstrap ‘self.run() File "/usr/1ib/python3.se/multiprocessing/process.py", Line 108, in run self. target(*self._args, **self._loargs) File "Gipython-dnput-2-2FFa6f04abed>", Line 22, in search worker resuits.extend(local_results) Traceback (most recent call last) ttriputetrron: ‘syncheonizedarray’ object has no attribute ‘extend File "/usr/Lib/pythen3.10/multiprocessing/process.py", Line 314, in _bootstrap self.run() File "Cipython-input-2-2FFa6f949be9>", Line 22, in search_worker rresults.extend(local_results) File "/usr/Lib/python3.ie/multiprocessing/process.py", Line 108, in run self. _target(*self._args, "*sel#,_joargs) AttriouteErron: ‘synchantzedarray' object has no attribute ‘extend Process Execution Time: 2.2296944489845852 seconds Speedup(Process): 1.977264801126165 + Threaded 1 # Threaded Search 2 threaded results, threaded tine = threaded search(target_elenent, data) a 4 print(“Threaded Execution Tine:", threaded tine, “seconds! 5 6 # Calculate speedup 7 threaded_speedup = sequential_tine / threaded_tine 8 print("Speedup(threaded):", threaded_speedup) ‘Threaded Execution Tine: ,7720451354980469 seconds Speedup(Threaded): 5.710411550643075, > Bar Graph - Execution Time 2 4 6 a 2° import matplotlib.pyplot as plt # Execution tines for the four functions execution times = [sequential tine, pool_tine, process_tine, threaded tine] functions = ["Sequential”, "Pool", "Process", "Threaded" plt.bar(functions, execution tines, color = plt.xlabel (“Functions”) plt.ylabel(*Execution Ties (seconds)") plt.title("Execution Times for Different Functions") plt.shox() red", "blue", ‘green’, ‘orange")Execution Times for Different Functions 'e) > Bar Graph - Speedup 18 calculate Speedup 2 sequential_speedup = sequentiai_tine / sequent: 3 pool_speedip = sequential tise 7 pool_tine 4 process speedup = sequential tine / process tire 5 threaded speedup = sequential_tine / threaded tite 9 print("Speedup(Process):", process_speedup) 20 print("Speedup(Threaded):", threaded speedup) £2 Inport natplotlib.pyplot as plt Execution times for the parailel and pool functions 25 Speedup = [process_tine, pool_tine] 36 fu ons = ["Process”, Pool”) 28 plt.bar(functions, Speedup, color = ["green*, "blue']) 29 plt.xlabel("Functions") 20 plt.ylabel( “Execution Tine (seconds)") 21 plttitle("Execution Times for Parallel and Pool Functions") 22 plt.show()Speedup(Process): 2.194@00400020958 Speedup(Threaded): ,640261580595983, Execution Times for Parallel and Pool Functions LAB-8(Write a python program to sort an array using sequential,pool,process and thread functions.Also, find speedup and draw respective graph.) 2 2o4 a | 1 Anmport tine 2 from tineit inport defau! 3 import multiprocessing as 44 mport nunpy as op 6 anport threading 7 import. random + Sequential co 1# Sequential Tine 2 start = tiner() 3 def bubble_sort(are) 4 n= len(arr) for & in range(n): 4 Flag to optinize the algoriths by stopping if there are no swaps in a pass swapped = False 5 a 2 F Last 4 elenants are already in place, so we don’t need to check them 1 for J in range(@, n-i-2): 2 Bf arel] > are{ ja} 3 6 2 48 Saap the elenents arr{J], are{ ea] = are[Je4], arty swapped = True 1 TF no two elenents were swapped in the inner loop, the array 1s already sorted 3 not swapped: 22 nylist = [randos.randint(1, 180) for _ in range(s@ee)] 23 result = bubble_sort(aylist) 24 end = tiner()-start 25 print(*Sequential Tine:",endi) Sequential Tine: 2.55i108608¢00007 > Pool 1 # Pool Thee Mangenent 2 start = tiner() 3 pool = p.Po0l() 4 resultt = pool.eap(bubble_sort, [mylist]) 5 end2 = tieer() - start 6 print(‘Pool Time: ,end2) Pocl Tine: 0.922057eese0e000183+ Process 1 Process Time Managenent 2 start = tiner() 3 p2 = mp.Process(target = bubble sort, args=(aylist,)) 4 p2.start() 5 p2.join() 6 end3 = tieer() - start 7 print("process Tine: *,end3) > Threaded 1 # thread Tine Managenent 2 start=tiner() 3 p3ethreading. Thread targe 4 p3.start() 5 endastiner()-start 6 print("Theead tine + “ends bubble_sort,args=(nylist,)) Tread tine: 0,0035427280000980027 > Bar Graph - Execution time 14 Tine Graph Plot 2hnaned = ['Sequentsal", "Pool", ‘Process’, Thread’ J 3 exe_tine = [endt, end2,ené3,ende) 4 pltsbar(nanet,exe_tine, color [‘red", "blue", ‘green’, ‘orange’ )) 5 plt.show() 25 20 as 10 os. oot Sequential Pool Process Thread > Bar Graph - Speedup 1 Speed up 2 speed _up_pool = endi/end23 speed _up_process = ondi/end3 44 speed_up_ thread = endi/enas s 6 print("speed up for Pool: *,speed_up_pool) 7 prant("Speed up for Process: °, peed_up_precess) 8 print("Speed up for Thread: *,Speed_op_thread) Speed up for Pool: 115.65937239666938 Speed up for Process: 139.70337969208375, Speed up for Thread: 1652.551764256751 1 wspeedup Graph 2 naned = [Pool Process”, "Thread" } 3 speed _up = [speed_up_pool, speed _up_process, speed up_thread] 4 5 plt.bar(nane2, speedup, color = ['red', "blue", “green")) 6 plt.show() 600 400 1200 1000 800 600 400 200 _ Fool Process ‘Thread LAB - 9(Write a Python Program to convert temperature from celsius to ~ fahrenheit. Calculate the sequential ,pool,process and thread time. Also, find speed up and draw graph using matplotlib) 1 import tine 2 from tineit inport default_tiner as tiner 43 Anport multiprocessing as =p 4 Smport nunpy as np 5 import matplotlib.pyplot as plt 6 Smport threading 7 Amport random > Sequential 1.4 Sequential Tine Manageeent 2 start = tiner() 3 dof celsius to fahrenheit (celsius): 4 fahrenheit = (celsius * 9/5) + 32 5 return fahrenheit64 _nane_ => “Lain 7 data = [randossrandine(@, n) for _ in range(s)) result = celsius_to_fehrenhest(cata) 9 endl = tiner()-start 28 print("Sequential Tine:*,end1) Sequential Tine: @.5026248960002708 + Pool 1 # Pool Tise Mangenent 2 start = timer() 3 pool = ep.Pc0}() 4 result = pool.sap(celsius to fahrenheit, (temp,)) 5 end2 = tiner() ~ start & print (‘Pool Tine: end) 7 Pool Time: 0.923791277998467612 > Process 1 # Process Time Management 2 start = timer() 3 p2~ mp.Process(target ~ celsius to fahrenheit, args~(terp,)) 4 pastart() 5 p2-Join() 6 ends = tiner() = stare 7 print(*process Tine: ' end3) process Tine: @.01861151599980581 ~ Threaded 1 # Thread Tine Managenent 3 p3threading. Thread(target-celstus_to_fahrenhett,args=(temp,)) 4 pa.start() 5 ende=tirer()-start, 6 print("Threas tine : *,ende) Thread tine : 0,00056254:0003773773 > Bar Graph - Execution time 1 # Tine Graph Plot 2 nanet = [Sequential "Pool", "Process',, ‘Thread’ 3 exe_tine = [end2, end2,end3,end¢) 4 plt.bar(nanet,exe_tine, color = [‘red', "blue", ‘green’, ‘orange")) 5 plt.show()os. oa 03 02 > Bar Graph - Speedup — 1.8 Speed up graph 2 nane2 = [Pool "Process", "Thread"] 43 speed_up = [speed_up_po0l, speed _up_process, speed_up_thread) 5 pt.tar(name, peep color= [red ble", gren")) epieston) 1600 1400 1200 1000 se0 609 200 Fool Process Thread
You might also like
3rd EXPERIMENT
PDF
No ratings yet
3rd EXPERIMENT
13 pages
Ge - Computer Science Data Analysis
PDF
No ratings yet
Ge - Computer Science Data Analysis
16 pages
Fda Lab
PDF
No ratings yet
Fda Lab
43 pages
Part1 Cours Python
PDF
No ratings yet
Part1 Cours Python
62 pages
Unit 4
PDF
No ratings yet
Unit 4
27 pages
Ip Xii Practical File 2023
PDF
No ratings yet
Ip Xii Practical File 2023
45 pages
OS Lab Python Programs
PDF
No ratings yet
OS Lab Python Programs
43 pages
OS Program
PDF
No ratings yet
OS Program
36 pages
FDS Record-1-4
PDF
No ratings yet
FDS Record-1-4
18 pages
Exercise 7 - Pandas
PDF
No ratings yet
Exercise 7 - Pandas
2 pages
Numpy
PDF
No ratings yet
Numpy
20 pages
AD3301 DEV Lab Manual
PDF
No ratings yet
AD3301 DEV Lab Manual
26 pages
MSBA315 Intro To Python For ML
PDF
No ratings yet
MSBA315 Intro To Python For ML
3 pages
Python GTU Study Material Presentations Unit-3 20112020032538AM
PDF
100% (1)
Python GTU Study Material Presentations Unit-3 20112020032538AM
70 pages
Module 4 Pandas File 1
PDF
No ratings yet
Module 4 Pandas File 1
3 pages
Numpy
PDF
No ratings yet
Numpy
28 pages
OCS353-Data Science Fundamentals Manual 1
PDF
No ratings yet
OCS353-Data Science Fundamentals Manual 1
34 pages
MCP Lab-2023 ContentForPythonLibrariesTopic
PDF
No ratings yet
MCP Lab-2023 ContentForPythonLibrariesTopic
9 pages
R20 Ai&ds 2ND B.tech Cse Intro To Ai&ds Lab Manual
PDF
No ratings yet
R20 Ai&ds 2ND B.tech Cse Intro To Ai&ds Lab Manual
1 page
Name: M.V.S.Sai Roshan Class: Cse-A ROLL NO: CH - EN.U4CSE21037
PDF
No ratings yet
Name: M.V.S.Sai Roshan Class: Cse-A ROLL NO: CH - EN.U4CSE21037
10 pages
Attachment 3 Python For Data Analysis Lyst9850
PDF
No ratings yet
Attachment 3 Python For Data Analysis Lyst9850
31 pages
Python Question Bank
PDF
No ratings yet
Python Question Bank
12 pages
ML Lab Manual (Upto Cie-1)
PDF
No ratings yet
ML Lab Manual (Upto Cie-1)
33 pages
PMI - Modules and Data Structures
PDF
No ratings yet
PMI - Modules and Data Structures
23 pages
Module 6 NumPY and Pandas
PDF
No ratings yet
Module 6 NumPY and Pandas
12 pages
GE - Computer Scien 4ogygeb
PDF
No ratings yet
GE - Computer Scien 4ogygeb
8 pages
2.4. NumPy Operations
PDF
No ratings yet
2.4. NumPy Operations
49 pages
University Institute of Engineering Department of Computer Science & Engineering
PDF
No ratings yet
University Institute of Engineering Department of Computer Science & Engineering
11 pages
Operating System With Python
PDF
No ratings yet
Operating System With Python
15 pages
Week1 - Introduction To Machine Learning and Toolkit
PDF
No ratings yet
Week1 - Introduction To Machine Learning and Toolkit
102 pages
Assignment 01
PDF
No ratings yet
Assignment 01
7 pages
Chapter 3 Python For Data Science
PDF
No ratings yet
Chapter 3 Python For Data Science
81 pages
DV Lab Manual Modified
PDF
No ratings yet
DV Lab Manual Modified
31 pages
ML Manual
PDF
No ratings yet
ML Manual
21 pages
Numpy
PDF
No ratings yet
Numpy
30 pages
Foundation of Data Science Lab Manual Full
PDF
No ratings yet
Foundation of Data Science Lab Manual Full
8 pages
ML Contenthalf
PDF
No ratings yet
ML Contenthalf
35 pages
E Data Analysis With Python Master Manual
PDF
No ratings yet
E Data Analysis With Python Master Manual
61 pages
Emerging Technologies
PDF
No ratings yet
Emerging Technologies
16 pages
Certificate That This Is Bonafide Record of Practical Work Done in The Laboratory by The Candidate P.Hemanth During The Academic Year 2022 - 2023
PDF
No ratings yet
Certificate That This Is Bonafide Record of Practical Work Done in The Laboratory by The Candidate P.Hemanth During The Academic Year 2022 - 2023
36 pages
CS3361-Data Science Lab Manual - B.rethina Kumar
PDF
No ratings yet
CS3361-Data Science Lab Manual - B.rethina Kumar
36 pages
Numpy
PDF
No ratings yet
Numpy
7 pages
ML Lab File Vijay Kumar
PDF
No ratings yet
ML Lab File Vijay Kumar
16 pages
EXP1-siddhant Gupta (23 - SE - 148)
PDF
No ratings yet
EXP1-siddhant Gupta (23 - SE - 148)
17 pages
Co Digit Ooo
PDF
No ratings yet
Co Digit Ooo
15 pages
PDC Experiments
PDF
No ratings yet
PDC Experiments
11 pages
Pandas Notes
PDF
No ratings yet
Pandas Notes
6 pages
DSC Lab Programs
PDF
No ratings yet
DSC Lab Programs
24 pages
HackyHour - Python Tips & Tricks
PDF
No ratings yet
HackyHour - Python Tips & Tricks
26 pages
Os Record BSC Program Only
PDF
No ratings yet
Os Record BSC Program Only
31 pages
Advanced Python Lab
PDF
No ratings yet
Advanced Python Lab
17 pages
Divp Pyq 2023
PDF
No ratings yet
Divp Pyq 2023
7 pages
4 Introduction To Python Part 3
PDF
No ratings yet
4 Introduction To Python Part 3
48 pages
L-1 (Introduction To Numpy & Panda) - Colab
PDF
No ratings yet
L-1 (Introduction To Numpy & Panda) - Colab
7 pages
Fundamentals of Data Science Lab Manual New1
PDF
No ratings yet
Fundamentals of Data Science Lab Manual New1
32 pages
Experiments
PDF
No ratings yet
Experiments
19 pages
Series
PDF
No ratings yet
Series
23 pages
ENGR691, Spring 2015, Homework For Lecture Block 1: 1 Code Listing
PDF
No ratings yet
ENGR691, Spring 2015, Homework For Lecture Block 1: 1 Code Listing
4 pages
Final DAA
PDF
No ratings yet
Final DAA
31 pages