我试图在以下类中运行timeit.timeit:
from contextlib import suppress
from pathlib import Path
import subprocess
from timeit import timeit
class BackupVolume():
'''
Backup a file system on a volume using tar
'''
targetFile = "bd.tar.gz"
srcPath = Path("/BulkData")
excludes = ["--exclude=VirtualBox VMs/*", # Exclude all the VM stuff
"--exclude=*.tar*"] # Exclude this tar file
@classmethod
def backupData(cls, targetPath="~"): # pylint: disable=invalid-name
'''
Runs tar to backup the data in /BulkData so we can reorganize that
volume. Deletes any old copy of the backup repository.
Parameters:
:param str targetPath: Where the backup should be created.
'''
# pylint: disable=invalid-name
tarFile\
= Path(Path(targetPath /
cls.targetFile).resolve())
with suppress(FileNotFoundError):
tarFile.unlink()
timeit('subprocess.run(["tar", "-cf", tarFile.as_posix(),'
'cls.excludes[0], cls.excludes[1], cls.srcPath.as_posix()])',
number=1, globals=something)我遇到的问题是,在timeit()中,它不能解释子进程。我认为globals参数到timeit()应该会有所帮助,但我不知道如何指定模块命名空间。有人能告诉我怎么做吗?
发布于 2018-03-08 11:21:57
我认为在您的例子中,globals = globals()在timeit调用中是可行的。
解释
globals参数指定要在其中执行代码的命名空间。由于您导入了subprocess模块(函数之外,甚至类之外),您可以使用globals()。在这样做时,您可以访问当前模块的字典,您可以找到更多的信息在文件中。
超级简单示例
在本例中,我将公开3种不同的场景。
遵循以下示例的代码:
import subprocess
from timeit import timeit
import math
class ExampleClass():
def performance_glob(self):
return timeit("subprocess.run('ls')", number = 1, globals = globals())
def performance_loc(self):
a = 69
b = 42
return timeit("a * b", number = 1, globals = locals())
def performance_mix(self):
a = 69
return timeit("math.sqrt(a)", number = 1, globals = {'math': math, 'a': a})performance_glob中,您在计时需要全局导入的东西,即模块subprocess。如果不传递globals名称空间,就会得到类似于以下NameError: name 'subprocess' is not defined的错误消息globals()传递给依赖于本地值的函数( performance_loc ),则时间执行a和b所需的变量将不在作用域中。这就是为什么你可以使用locals()globals指定为字典,只需提供必要的键,就可以自定义它。https://stackoverflow.com/questions/44890932
复制相似问题