Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...