I am trying to efficiently deep copy a numpy array into another.
Some background, I started with copying from a byte array into the numpy array like the following. However, this took around 0.9ms on average
#Sample Setup
import mmap
import numpy as np
import copy
import random
src_bytes=bytes([random.randint(0,255) for i in range(0,4096)])
#src_bytes is of type bytes and len = 4096
mmem = mmap.mmap(-1, len(src_bytes))
dest_np = np.ndarray(shape=(len(src_bytes)), dtype=np.uint8, buffer=mmem)
for (idx, data) in enumerate(src_bytes):
dest_np[idx] = np.uint8(data)
As this was inefficient, I alternatively tried the following two methods:
Method1, which takes around 0.016ms on average
src_bytes = np.frombuffer(src_bytes,dtype=np.uint8)
dest_np[:] = src_bytes
Method2, which took around 0.040ms on average
src_bytes = np.frombuffer(src_bytes,dtype=np.uint8)
dest_np = copy.deepcopy(src_bytes)
For me Method1 seems to be giving the better result, but I am not aware of the underlying implementation. Is this a good and right way to (deep) copy those arrays?
Might I also ask if both these methods are correct alternatives to what I was doing originally (using a for loop to copy individual values)?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…