我在 Linux 机器上运行 Python 2.7,到目前为止,我的脚本中最慢的部分是使用 ujson 从磁盘(SSD)加载一个大的 json 文件。图书馆。当我在这个加载过程中检查 top
时,我的 cpu 使用率基本上是 100%,这让我相信我遇到瓶颈是解析 json 而不是将字节从磁盘传输到内存。这是一个有效的假设,还是 ujson 在等待磁盘时会烧掉空循环或其他东西?我很想知道,因为我不确定将我的 cpu 的另一个核心专用于另一个执行大量磁盘 i/o 的脚本是否会显着降低第一个脚本的速度。
最佳答案
没有看到你的代码,我会假设你正在做这样的事情:
with open('data.json') as datafile:
data = json.loads(datafile.read())
相反,您可以拆分读取文件和解析文件的步骤:
with open('data.json') as datafile:
raw_data = datafile.read()
data = json.loads(raw_data)
如果你添加一些计时调用,你可以确定每一步需要多长时间:
# Timing decorator from https://www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.2f sec' % \
(method.__name__, args, kw, te-ts)
return result
return timed
with open('data.json') as datafile:
@timeit
raw_data = datafile.read()
@timeit
data = json.loads(raw_data)
关于python - 诊断我何时受磁盘 i/o 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33572025/