Created
September 29, 2021 18:52
-
-
Save evjeny/0d6f165a9596bd7ab9301dc2f98c925a to your computer and use it in GitHub Desktop.
Multiprocessing demo
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
""" | |
Какая-то библиотека, в которой есть затратная по времени функция | |
""" | |
def very_slow_function(n: int) -> int: | |
return n ** 1000 |
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 time | |
from multiprocessing import Pool, cpu_count | |
from lib import very_slow_function | |
""" | |
будем параллельно вызывать функцию | |
(одновременно на нескольких ядрах процессора) | |
""" | |
n_operations = 100_000 | |
result = {} | |
# замеряем время начала | |
t_begin = time.time() | |
# заранее подготовим список аргументов, на которых | |
# должна отработать функция | |
arguments = list(range(n_operations)) | |
""" | |
объект Pool -- это обертка над несколькими ядрами. | |
по сути, у тебя будет запущено несколько экземпляров программы. | |
сколько именно? -- cpu_count() (`cpu_count` возвращает число ядер CPU) | |
""" | |
with Pool(cpu_count()) as pool: | |
""" | |
после выполнения функция map вернет значения функции | |
на аргументах `arguments` в том порядке, | |
в котором они находятся в спике `arguments` | |
""" | |
result = pool.map(very_slow_function, arguments) | |
""" | |
zip позволяет проитерироваться по нескольким последовательностям одновременно. | |
в данном случае значение `i` будет получено из `arguments`, | |
а значение `f_i` -- из `result` | |
""" | |
for i, f_i in zip(arguments, result): | |
result[i] = f_i | |
# замеряем время конца | |
t_end = time.time() | |
print("Multiple processes benchmark") | |
print("Benchmarked {n} operations for {t} s".format(n=n_operations, t=round(t_end - t_begin, 5))) |
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 time | |
from lib import very_slow_function | |
# будем вызывать функцию на аргументах от 0 до 100 000 | |
n_operations = 100_000 | |
result = {} | |
# замеряем время начала | |
t_begin = time.time() | |
for i in range(n_operations): | |
# просто вызываем функцию от каждого аргумента по очереди | |
result[i] = very_slow_function(i) | |
# замеряем время конца | |
t_end = time.time() | |
print("Single process benchmark") | |
print("Benchmarked {n} operations for {t} s".format(n=n_operations, t=round(t_end - t_begin, 5))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment