Files
controller-data-analysis/test/test_asyncio_multi_process.py
T
2023-02-13 17:17:42 +08:00

81 lines
2.4 KiB
Python

import concurrent.futures
import math
import time
import asyncio
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
async def my_async_func(arg):
return is_prime(arg)
def sync_wrapper(arg):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(my_async_func(arg))
loop.close()
return result
# def main():
# start = time.time()
# # Use the sync_wrapper function with Executor.map
# with concurrent.futures.ProcessPoolExecutor() as executor:
# for number, prime in zip(PRIMES, executor.map(sync_wrapper, PRIMES)):
# print('%d is prime: %s' % (number, prime))
# # process
# # with concurrent.futures.ProcessPoolExecutor() as executor:
# # for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
# # print('%d is prime: %s' % (number, prime))
# # thread
# # with concurrent.futures.ThreadPoolExecutor() as executor:
# # for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
# # print('%d is prime: %s' % (number, prime))
# #single
# # for prime in PRIMES:
# # print(prime, is_prime(prime))
# print('done', time.time() - start)
async def main():
start = time.time()
# Use the sync_wrapper function with Executor.map
with concurrent.futures.ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(sync_wrapper, PRIMES)):
print('%d is prime: %s' % (number, prime))
# process
# with concurrent.futures.ProcessPoolExecutor() as executor:
# for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
# print('%d is prime: %s' % (number, prime))
# thread
# with concurrent.futures.ThreadPoolExecutor() as executor:
# for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
# print('%d is prime: %s' % (number, prime))
#single
# for prime in PRIMES:
# print(prime, is_prime(prime))
print('done', time.time() - start)
if __name__ == '__main__':
# main()
asyncio.run(main())