Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (31.9m points)

python 3.x - What is the difference between dest_np=copy.deepcopy(src_np) and dest_np[:]=src_np for copying numpy arrays in python3? Which is better?

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)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (31.9m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...