首页 > 解决方案 > python3 NamedTemporaryFile 的写入速度比 gcloud 实例上的普通文件慢得多

问题描述

我使用下面的代码来 tar 一个大约 1G 的文件夹。需要30多秒才能完成

import tarfile
import tempfile

# tar the folder
tmp_path = 'my_folder'

f_temp = tempfile.NamedTemporaryFile()
src_fname = f_temp.name
with tarfile.open(src_fname, "w") as tar:
    tar.add(tmp_path, arcname='.')

但是,如果我tar cf my_folder在终端中使用,它只需要一秒钟多一点。

如果我使用普通文件,python 脚本也需要不到 2 秒。

import tarfile

# tar the folder
tmp_path = 'my_folder'

src_fname = 'nos.tar'
with tarfile.open(src_fname, "w") as tar:
    tar.add(tmp_path, arcname='.')

为什么速度如此不同?在我的情况下,临时文件和临时文件nos.tar都被写入同一个设备/dev/sda1。该计算机n1-standard-4/nvidia-tesla-v100/1us-central1-a.

这种放缓似乎与 gcloud 实例有关。我在本地计算机上尝试了上述3种方法,即

所有这些都在 2 秒内完成。第二种方法比第一种慢约 0.4 秒,第三种比第一种慢约 0.4 秒,这在另一个 stackoverflow 帖子中有所提及。

在 gcloud 实例tempfile.NamedTemporaryFile()上,/tmp我将常规文件写入/scratch.

nos@instance:/scratch$ df -h /scratch/
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        31G  2.2G   29G   7% /
nos@instance:/scratch$ df -h /tmp/
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        31G  2.2G   29G   8% /

两者都指向同一个设备,但速度似乎指示不同的设备。

标签: python-3.xgcloudtemporary-files

解决方案


推荐阅读