如何分别测量函数的 CPU 运行时间和挂钟运行时间,作为 Python 代码(不是来自终端)? [英] How to measure CPU running time and wall clock running time of a function, separately, as Python code (not from terminal)?

查看:64
本文介绍了如何分别测量函数的 CPU 运行时间和挂钟运行时间,作为 Python 代码(不是来自终端)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来衡量 Python 中的函数性能,将挂钟和 CPU 时间分开.

I'm looking for a way to measure function performance in Python, separating wall clock and CPU time.

我研究了 python 分析器,但它们似乎旨在扫描程序而不是单独的功能.来自 http://docs.python.org/2/library/profile.html :

I've looked into the python profilers, but they seem to be designed to scan a program and not functions alone. From http://docs.python.org/2/library/profile.html :

注意分析器模块旨在为给定程序提供执行配置文件,而不是用于基准测试目的(为此,有时间以获得合理准确的结果).这尤其适用于针对 C 代码对 Python 代码进行基准测试:分析器会为 Python 代码引入开销,但不会为 C 级函数引入开销,因此 C 代码似乎比任何 Python 代码都快.

Note The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is timeit for reasonably accurate results). This particularly applies to benchmarking Python code against C code: the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one.

然后我尝试了 timeit 模块:http://docs.python.org/2/library/timeit.html ,但它似乎不支持 CPU 和挂钟时间的分离.据我了解,它只是衡量总运行时间.

I then tried the timeit module: http://docs.python.org/2/library/timeit.html , but it doesn't seem to support separation of CPU and wall clock time. As I understand, it just measures total run time.

我正在寻找的是这样的:

What I'm looking for is something like this:

$ time python yourprogram.py

real    0m1.028s
user    0m0.001s
sys     0m0.003s

但不是从命令行调用它,我需要从 python 代码调用它.

But instead of calling it from command line, I need to call it from python code.

类似于 R 中的 system.time():

Something like system.time() in R:

print(system.time(replicate(repeats, factorialRecursive(150))))
 user  system elapsed 
0.041   0.001   0.041 

我如何在 Python 中实现这一点?

How can I achieve this in Python?

推荐答案

resource 模块 包含 getrusage,它应该允许您分别检索用户、系统和挂钟时间,就像 time命令执行.

The resource module houses getrusage, which should allow you to retrieve user, system, and wall-clock time separately, just as the time command does.

这篇关于如何分别测量函数的 CPU 运行时间和挂钟运行时间,作为 Python 代码(不是来自终端)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆