Skip to main content
 首页 » 编程设计

python之高磁盘使用率是否意味着更快的文件读/写操作

2024年10月01日7pander-it

我正在编写一个 python 脚本,我在其中逐行读取一个大约 5 GB 的大文件,对每一行进行一些修改,然后将其写入另一个文件。

当我使用函数 file.readlines() 读取输入文件时,我的磁盘使用率达到 ~90% 并且磁盘速度达到 +100Mbps(我知道这种方法不应该用于大文件)。

我没有测量上述情况下的程序执行时间,因为我的系统变得无响应(内存已满)。

当我使用像下面这样的迭代器时(这就是我在代码中实际使用的)

with open('file.csv', 'r') as inFile: 
    for line in inFile: 

我的磁盘使用率仍然低于 10%,速度低于 5 Mbps,程序完成执行一个 5 GB 的文件大约需要 20 分钟。如果我的磁盘使用率很高,这个时间会不会更低?

此外,读取 5 GB 是否真的需要大约 20 分钟,逐行处理,对每一行进行一些修改,最后将其写入新文件,还是我做错了什么?

我不明白的是为什么程序在执行 io 操作时没有充分利用我的系统的潜力。因为如果是这样,那么我的磁盘使用率应该更高,对吧?

请您参考如下方法:

我不认为你的主要问题是读取文件,因为你正在使用 open(),相反我会检查你在这里做什么:

make some modifications in each of the lines, and then write it to another file.

因此,尝试在不对另一个文件进行修改/写入修改的情况下读取该文件,以了解您的系统仅读取该文件需要多少时间。

这是我在阅读 this 后在我的环境中进行测试的方式, this , this和 this

首先,创建一个 1.2GB 的文件:

timeout 5 yes "Ergnomic systems for c@ts that works too much" >> foo 

我没有使用 dd 或 truncate,这会在读取文件时导致内存错误。

现在一些 I/O 测试读取文件,这是一个已经优化的操作,就像 @Serge Ballesta 提到的:

#!/usr/bin/python 
with open('foo') as infile: 
    for line in infile: 
        pass 
    print 'file readed' 
 
$ time python io_test.py 
file readed 
 
real    0m2.647s 
user    0m2.343s 
sys     0m0.327s 

使用 open() 更改缓冲选项:

# --------------------------------------NO BUFFERING 
with open('foo','r',0) as infile: 
    for line in infile: 
        pass 
    print 'file readed' 
 
$ time python io_test.py 
file readed 
 
real    0m2.787s 
user    0m2.406s 
sys     0m0.374s 
 
# --------------------------------------ONE LINE BUFFERED 
with open('foo','r',1) as infile: 
  for line in infile: 
    pass 
  print 'file readed'  
 
$ time python io_test.py 
file readed 
 
real    0m4.331s 
user    0m2.468s 
sys     0m1.811s 
# -------------------------------------- 70 MB/s 
with open('foo','r',700000000) as infile: 
  for line in infile: 
    pass 
  print 'file readed'  
 
$ time python io_test.py 
file readed 
 
real    0m3.137s 
user    0m2.311s 
sys     0m0.827s 

为什么不应该使用 readlines:

with open('foo') as f: 
    lines = f.readlines() 
    for line in lines: 
        pass 
 
$ time python io_test.py 
 
real    0m6.428s 
user    0m3.858s 
sys     0m2.499s