LoginSignup
0
0

同時に処理を実行して高速プログラムを書こう!

Last updated at Posted at 2023-12-31

速度改善で悩まれている方は多いと思います。
今回は速度改善の手法として並列処理と並行処理を紹介します。

※今回紹介する並列処理と並行処理を組み込むには特別なライブラリのインストールは必要とせず、
Pythonの標準ライブラリで対応することができます。

通常の処理と並列処理と並行処理を比較するにあたり、以下を理解する必要があります。
※前提条件として処理Aと処理Bが存在する。

処理名 詳細
通常の処理 順番に処理を行う。処理Aが終了次第、処理Bが実行される。
並列処理 処理Aと処理Bの同時に処理を実行し、結果が出たもの順に出力する。
並行処理 処理Aと処理Bを細かく分割し、AとBを効率よく切り替えて処理する。

利用PCの処理性能が高いことに加え、簡易なプログラムのため、
並列処理と並行処理の差分があまりないですが、実行速度を比較していきます。

処理方法 実行速度
通常の処理 11.012077569961548
並列処理 6.057596921920776
平行処理 6.009162187576294

通常の処理

プログラム

import time

def fun1():
  time.sleep(1)
  print("a")
  time.sleep(5)
  print("c")

def fun2():
  time.sleep(2)
  print("b")
  time.sleep(3)
  print("d")

def main():
  start = time.time()
  fun1()
  fun2()
  end = time.time()
  time_diff = end - start
  print(time_diff)

main()

実行結果

a
c
b
d
11.012077569961548

並行処理

プログラム

import time
import concurrent.futures 

def fun1():
  time.sleep(1)
  print("a")
  time.sleep(5)
  print("c")

def fun2():
  time.sleep(2)
  print("b")
  time.sleep(3)
  print("d")

def main():
  start = time.time()
  with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor:
    executor.submit(fun1)
    executor.submit(fun2)
  end = time.time()
  time_diff = end - start
  print(time_diff)

main()

結果

a
b
d
c
6.057596921920776

並列処理

プログラム

import time
import concurrent.futures

def fun1():
  time.sleep(1)
  print("a")
  time.sleep(5)
  print("c")

def fun2():
  time.sleep(2)
  print("b")
  time.sleep(3)
  print("d")

def main():
  start = time.time()
  with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
    executor.submit(fun1)
    executor.submit(fun2)
  end = time.time()
  time_diff = end - start
  print(time_diff)

main()

結果

a
b
d
c
6.009162187576294
0
0
0

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
0
0