- В большинстве случаев кэшированная версия работает медленнее, чем просто выполнение всех вычислений.
- Мало того, что кэшированная версия работает медленнее, профилирование строк также показывает, что абсолютное время, затрачиваемое на числовые операции, увеличивается, даже если их меньше.
Полное приложение сложное, но поведение можно воспроизвести с помощью следующего:
Код: Выделить всё
import numpy as np
from time import time
def numpy_comparison(do_cache: bool, array_size: int, num_arrays: int, num_iter: int):
# Create random arrays
arrays: dict[int, np.ndarray] = {}
for i in range(num_arrays):
arrays[i] = np.random.rand(array_size)
if do_cache: # Set up the cache if needed - I cannot use lru_cache or similar in practice
cache: dict[tuple[int, int], np.ndarray] = {}
for _ in range(num_iter): # Loop over random pairs of array, add, store if relevant
i, j = np.random.randint(num_arrays, size=2)
if do_cache and (i, j) in cache:
a = cache[(i, j)] # a is not used further here, but would be in the real case
else:
a = arrays[i] + arrays[j]
if do_cache:
cache[(i, j)] = a
Код: Выделить всё
%timeit numpy_comparison(do_cache=False, array_size=10000, num_arrays=100, num_iter=num_iter)
%timeit numpy_comparison(do_cache=True, array_size=10000, num_arrays=100, num_iter=num_iter)
< /code>
дает следующие результаты < /p>
< thead>
num_iter < /th>
без кэширования < /th>
с кэшированием < /th>
< /tr>
< /thead>
100 < /td>
td>10.3ms
13.7ms
< /tr>
1000 < /td>
28.8 ms < /td>
62.7ms
< /tr>
10000 < /td>
< TD> 225 мс < /td>
392 мс < /td>
< /tr>
100000 < /td>
2.12S
1.62s>
изменяет размер массива, а количество массивов дает аналогичное поведение. Когда num_iter Может ли кто -нибудь дать намек на то, что здесь происходит? /п>
Подробнее здесь: https://stackoverflow.com/questions/793 ... lculations
Мобильная версия