python - 如何提高Python从磁盘读取的速度

标签 python

我使用 Python 进行图像分析。我的代码的第一步是将图像从磁盘加载到一个大的 20GB uint8 数组中。这一步花费的时间很长,加载大约10MB/s,并且任务期间CPU处于空闲状态。

这看起来非常慢。我犯了一个明显的错误吗?我怎样才能提高性能?是numpy数组类型的问题吗?

# find all image files in working folder
FileNames = []      # FileNames is a list of image names
workingFolder = 'C:/folder'
for (dirpath, dirnames, filenames) in os.walk(workingFolder):
     FileNames.extend(filenames)
FileNames.sort() # Sorted by image number 
 imNumber = len(FileNames) # Number of Images

 # AllImages initialize
 img = Image.open(workingFolder+'/'+FileNames[0])
 AllImages = np.zeros((img.size[0],img.size[1], imNumber),dtype=np.uint8)

 for ii in range(imNumber):
     img = Image.open(workingFolder+'/'+FileNames[ii])
     AllImages[:,:,ii] = img

非常感谢您的帮助。

最佳答案

由于 CPU 处于空闲状态,因此听起来磁盘是瓶颈。 10 Mb/s 有点慢,但还没有慢到让我想起石器时代的硬盘。如果是numpy我预计 CPU 会忙于运行 numpy代码而不是闲着。

请注意,CPU 等待磁盘的方式可能有两种。当然,首先您需要从磁盘读取数据,但由于数据为 20GB,因此数据可能足够大,需要将其交换到磁盘。这种情况的正常解决方案是对文件进行内存映射(这将避免将数据从磁盘移动到交换区)。

尝试检查是否可以通过其他方式更快地读取文件。例如,在 Linux 上您可以使用 dd if=/path/to/image of=/tmp/output bs=8k count=10k; rm -f /tmp/output检查读取内存的速度。请参阅this question有关检查磁盘性能的更多信息。

关于python - 如何提高Python从磁盘读取的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31556274/

相关文章:

python - 解析器错误 : hour must be in 0. .23: 09/05/2019 24:00

python - 在 Windows 中使用 python 获取 ipconfig 结果

python - 如何告诉 flask-admin 在显示外键字段时使用替代表示?

python - python中列表的可变性

python - 在Python中使用Beautifulsoup和Urllib2,如何找到特定标签包围的数据?

python - 位串相似度得分

python - 如何获取 pandas 中的行索引?

python - 根据纬度和经度过滤数据 - Numpy

python - 自动创建列表并追加元素

python - 使用 pandas/matplotlib 使用 for 循环创建条形图