53
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ちょっとかしこいtqdm② ~ multiprocessing編 ~

Last updated at Posted at 2019-01-04

tqdm

https://github.com/tqdm/tqdm
tqdm.gif

マルチプロセス×tqdmな記事があんましなかったので。

拙記事↓の続編(?)
ちょっとかしこいtqdm① ~ metricsの表示 ~

やりたいこと

  • 各データに何かしらの処理をしたい
import os
import time

start = time.time()

# 1秒待つ&二乗を返す関数
def f(x):
    time.sleep(1)
    value = x * x
    print('{}s passed...\t{}\t(pid:{})'.format(
        int(time.time() - start), value, os.getpid()))

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for d in data:
    f(d)

Screenshot from 2019-01-04 17-00-05.png

  • 大変だ!10秒かかってしまった!

普通のmultiprocessing

from multiprocessing import Pool
import os
import time

start = time.time()

# 1秒待つ&二乗を返す関数
def f(x):
    time.sleep(1)
    value = x * x
    print('{}s passed...\t{}\t(pid:{})'.format(
        int(time.time() - start), value, os.getpid()))

pool = Pool(processes=10)

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

with pool as p:
    p.map(f, data)

Screenshot from 2019-01-04 17-05-40.png

  • 1秒!天才!
  • でもこれどうやってtqdmするんすか?

multiprocessingなtqdm

from multiprocessing import Pool
import os
import time
from tqdm import tqdm

# 1秒待つ&二乗を返す関数
def f(x):
    time.sleep(1)
    value = x * x

pool = Pool(processes=10)

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

with tqdm(total=len(data)) as t:
    for _ in pool.imap_unordered(f, data):
        t.update(1)

Screenshot from 2019-01-04 17-07-48.png

  • できた

参考

最後に

以上っ!

53
26
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?