import time import multiprocessing def totaltime(ct): st = time.time() a = 100.33 b = 23.33 for v in range(ct): b = 1 + b c = a * b print("total time:", time.time()-st) ct = 25000000 if __name__ == '__main__': for i in range(multiprocessing.cpu_count()): p = multiprocessing.Process(target=totaltime, args=(ct,)) p.start() for p in multiprocessing.active_children(): print('Child process name: ' + p.name + ' id: ' + str(p.pid))
这段代码以前要 5s ,现在同一台机器只要 3s 了
import sys, time stdout = sys.stdout BAILOUT = 16 MAX_ITERATIOnS= 1000 class Iterator: def __init__(self): print('Rendering...') for y in range(-39, 39): stdout.write('\n') for x in range(-39, 39): i = self.mandelbrot(x/40.0, y/40.0) if i == 0: stdout.write('*') else: stdout.write(' ') def mandelbrot(self, x, y): cr = y - 0.5 ci = x zi = 0.0 zr = 0.0 i = 0 while True: i += 1 temp = zr * zi zr2 = zr * zr zi2 = zi * zi zr = zr2 - zi2 + cr zi = temp + temp + ci if zi2 + zr2 > BAILOUT: return i if i > MAX_ITERATIONS: return 0 t = time.time() Iterator() print('\nPython Elapsed %.02f' % (time.time() - t))
这段以前要 1.2s ,现在同一台机器只要 0.95s 了
1 PythonAnswer 2017-01-12 03:21:01 +08:00 跟 2.7 比比? |
![]() | 2 imn1 2017-01-12 08:14:09 +08:00 @PythonAnswer 你不能要求 win10 跟 win xp 比的 |
![]() | 5 Ahri 2017-01-12 09:03:38 +08:00 运行 1000 遍取平均值再说 |
![]() | 6 daimoon 2017-01-12 09:24:07 +08:00 python2 -V Python 2.7.10 python2 t1.py Child process name: Process-1 id: 697 Child process name: Process-3 id: 699 Child process name: Process-4 id: 700 Child process name: Process-2 id: 698 ('total time:', 11.26904296875) ('total time:', 11.378209829330444) ('total time:', 11.391005039215088) ('total time:', 11.501654863357544) python3 -V Python 3.5.1 python3 t1.py Child process name: Process-1 id: 707 Child process name: Process-4 id: 710 Child process name: Process-2 id: 708 Child process name: Process-3 id: 709 total time: 8.77907681465149 total time: 8.84126591682434 total time: 8.84130597114563 total time: 8.845878839492798 |
7 dracarysX 2017-01-12 09:29:02 +08:00 有可能是 range 的问题。 python3 优化了 range ,返回的是一个迭代器。 |
![]() | 8 daimoon 2017-01-12 09:29:45 +08:00 python3.6 t1.py Child process name: Process-2 id: 1191 Child process name: Process-1 id: 1190 Child process name: Process-3 id: 1192 Child process name: Process-4 id: 1193 total time: 6.99714207649231 total time: 7.0236029624938965 total time: 7.036419868469238 total time: 7.042246103286743 |
![]() | 9 daimoon 2017-01-12 09:31:49 +08:00 测试代码改为: xrange 。 python2 t1.py Child process name: Process-1 id: 1234 Child process name: Process-3 id: 1236 Child process name: Process-4 id: 1237 Child process name: Process-2 id: 1235 ('total time:', 6.006057024002075) ('total time:', 6.011800050735474) ('total time:', 6.023754119873047) ('total time:', 6.047795057296753) |
![]() | 10 daimoon 2017-01-12 09:32:13 +08:00 python3 任重道远啊。 |
11 Allenqjy 2017-01-12 09:43:17 +08:00 via iPhone 赶快干死 2.7 |
![]() | 12 gimp 2017-01-12 10:20:42 +08:00 py3 中的 range 就是 py2 中的 xrange |