#Python numerical integrator import multiprocessing as mp import time start_time = time.time() def f(x): return x**2 def integral(a, b, num, output): area = 0 index = a #start at the left endpoint interval = 1/num while index < b: area += f(index) * interval index += interval output.put(area) #return the area back to the parent program start = 1 end = 4 num_rectangles = 10000000 #number of independant processes to run num_processes = 100 # Setup a list of processes that we want to run processes = [] # Define an output queue output = mp.Queue() for i in range(num_processes): sub_a = ((end - start) / float(num_processes)) * i + start sub_b = sub_a + ((end - start) / float(num_processes)) sub_num = num_rectangles / num_processes processes.append(mp.Process(target=integral, args=(sub_a, sub_b, sub_num, output))) # Run processes for p in processes: p.start() # Exit the completed processes for p in processes: p.join() # Get process results from the output queue results = sum(output.get() for p in processes) print("Area %s" %(results)) print ("elapsed time: %s seconds" %(round(time.time() - start_time, 3)))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question