|
| 1 | +import time |
| 2 | +from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor |
| 3 | + |
| 4 | +def gcd(pair): |
| 5 | + ''' |
| 6 | + 求解最大公约数 |
| 7 | + ''' |
| 8 | + a, b = pair |
| 9 | + low = min(a, b) |
| 10 | + for i in range(low, 0, -1): |
| 11 | + if a % i == 0 and b % i == 0: |
| 12 | + return i |
| 13 | + |
| 14 | + assert False, "Not reachable" |
| 15 | + |
| 16 | +# 待求解的数据 |
| 17 | +NUMBERS = [ |
| 18 | + (1963309, 2265973), (5948475, 2734765), |
| 19 | + (1876435, 4765849), (7654637, 3458496), |
| 20 | + (1823712, 1924928), (2387454, 5873948), |
| 21 | + (1239876, 2987473), (3487248, 2098437), |
| 22 | + (1963309, 2265973), (5948475, 2734765), |
| 23 | + (1876435, 4765849), (7654637, 3458496), |
| 24 | + (1823712, 1924928), (2387454, 5873948), |
| 25 | + (1239876, 2987473), (3487248, 2098437), |
| 26 | + (3498747, 4563758), (1298737, 2129874) |
| 27 | +] |
| 28 | + |
| 29 | +if __name__ == '__main__': |
| 30 | + ## 顺序求解 |
| 31 | + start = time.time() |
| 32 | + results = list(map(gcd, NUMBERS)) |
| 33 | + end = time.time() |
| 34 | + delta = end - start |
| 35 | + print(f'顺序执行时间: {delta:.3f} 秒') |
| 36 | + |
| 37 | + ## 多线程求解 |
| 38 | + start = time.time() |
| 39 | + pool1 = ThreadPoolExecutor(max_workers=4) |
| 40 | + results = list(pool1.map(gcd, NUMBERS)) |
| 41 | + end = time.time() |
| 42 | + delta = end - start |
| 43 | + print(f'并发执行时间: {delta:.3f} 秒') |
| 44 | + |
| 45 | + ## 并行求解 |
| 46 | + start = time.time() |
| 47 | + pool2 = ProcessPoolExecutor(max_workers=4) |
| 48 | + results = list(pool2.map(gcd, NUMBERS)) |
| 49 | + end = time.time() |
| 50 | + delta = end - start |
| 51 | + print(f'并行执行时间: {delta:.3f} 秒') |
0 commit comments