Last active
October 26, 2015 15:52
-
-
Save k5trismegistus/9528653438037efdac52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import time | |
import functools | |
from multiprocessing import Pool | |
def Timer(func): | |
@functools.wraps(func) | |
def Wrapper(*args, **kw): | |
stime = time.clock() | |
ret = func(*args, **kw) | |
etime = time.clock() | |
print('{0}: {1:,f}ms'.format(func.__name__, (etime-stime)*1000)) | |
return ret | |
return Wrapper | |
def dice(iter): | |
time.sleep(1) | |
return random.randint(1, 6) | |
@Timer | |
def parallel(): | |
with Pool() as pool: | |
results_set = pool.map(dice, range(100)) | |
print(sum(results_set) / len(results_set)) | |
@Timer | |
def serial(): | |
results_set = [] | |
for x in range(100): | |
results_set.append(dice(x)) | |
print(sum(results_set) / len(results_set)) | |
if __name__ == '__main__': | |
parallel() | |
serial() | |
# 3.27 | |
# parallel: 28,240.931231ms | |
# 3.49 | |
# serial: 100,044.868033ms | |
# | |
# 並列計算版のほうが圧倒的に早い! | |
# でもsleepをなくしてみると直列のほうが早い | |
# | |
# 3.46 | |
# parallel: 153.485311ms | |
# 3.6 | |
# serial: 0.365031ms | |
# | |
# あまりにも簡単な計算の場合、並列計算の準備コストのほうがでかい |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment