I've seen several posts here about accessing individual items in numpy arrays and python lists via a for loop.
My program is a little different. What I'm doing is copying a small array (or list) of about 10 elements and then using it. I'm doing this many times, so I want it to be fast. The application if you're interested is that I'm searching a tree, and each small array/list is a 'state' in the tree.
But I'm finding that the numpy.copy() function is slower than the Python list() function.
To demonstrate what I'm saying, here's a small program with timings:
import time
import numpy as np
def numPyArrays(iterations:int):
initialArray = np.array([1,0,0,1,0,1,1,1,0,0])
for i in range(iterations):
nextArray = initialArray.copy()
print(f"Numpy Arrays:\n{nextArray}")
return
def pythonLists(iterations:int):
initialList = [1,0,0,1,0,1,1,1,0,0]
for i in range(iterations):
nextList = list(initialList)
print(f"Python Lists:\n{nextList}")
return
def main():
numIterations = 10000000
startTime = time.time()
numPyArrays(numIterations)
print(f"Time taken: {round(time.time() - startTime, 2)} seconds.\n")
startTime = time.time()
pythonLists(numIterations)
print(f"Time taken: {round(time.time() - startTime, 2)} seconds.\n")
main()
Timings:
Numpy Arrays:
[1 0 0 1 0 1 1 1 0 0]
Time taken: 4.68 seconds.
Python Lists:
[1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
Time taken: 1.5 seconds.
I would have thought the numpy.copy function would have been as fast as a list copy.
EDIT: For those wanting to know what the underlying problem is, it's an Advent of Code problem. Day 19, 2022. https://adventofcode.com/2022/day/19
np.arraytakes more time than creating a newlist. With 10 elements, mainly the effort required for this is measured. Compare your benchmark with arrays/lists of size 1, 10 (no measurable difference between 1 and 10), 100, 1000, 10000.