首页 > 其他分享 >ProcessPoolExecutor in concurrent

ProcessPoolExecutor in concurrent

时间:2023-01-19 17:57:03浏览次数:39  
标签:ProcessPoolExecutor seconds futures concurrent something time print

Simple example

import time
import concurrent.futures

start = time.perf_counter()

def do_something(seconds):
	print(f'sleeping {seconds} second(s)...')
	time.sleep(seconds)
	return f'Done sleeping...{seconds}'


f1 = executor.submit(do_something, 1)
f2 = executor.submit(do_something, 1)

print(f1.result())
print(f2.result())


finish = time.perf_counter()

print(f'Finish in {round(finish-start,2)} seconds(s)')

For循环

import time
import concurrent.futures

start = time.perf_counter()

def do_something(seconds):
	print(f'sleeping {seconds} second(s)...')
	time.sleep(seconds)
	return f'Done sleeping...{seconds}'

with concurrent.futures.ProcessPoolExecutor() as executor:
	results = [executor.submit(do_something,1) for _ in range(10)]

	for f in concurrent.futures.as_completed(results):
		print(f.result())

finish = time.perf_counter()

print(f'Finish in {round(finish-start,2)} seconds(s)')
import time
import concurrent.futures

start = time.perf_counter()

def do_something(seconds):
	print(f'sleeping {seconds} second(s)...')
	time.sleep(seconds)
	return f'Done sleeping...{seconds}'

with concurrent.futures.ProcessPoolExecutor() as executor:
	secs = [5,4,3,2,1]
	results = [executor.submit(do_something,sec) for sec in secs]

	for f in concurrent.futures.as_completed(results):
		print(f.result())



finish = time.perf_counter()

print(f'Finish in {round(finish-start,2)} seconds(s)')

map函数

import time
import concurrent.futures

start = time.perf_counter()

def do_something(seconds):
	print(f'sleeping {seconds} second(s)...')
	time.sleep(seconds)
	return f'Done sleeping...{seconds}'

with concurrent.futures.ProcessPoolExecutor() as executor:
	secs = [5,4,3,2,1]
	results = executor.map(do_something,secs)

	for result in results:
		print(result)

finish = time.perf_counter()

print(f'Finish in {round(finish-start,2)} seconds(s)')

标签:ProcessPoolExecutor,seconds,futures,concurrent,something,time,print
From: https://www.cnblogs.com/conpi/p/17061900.html

相关文章