计算python中代码的计算时间和内存

haf*_*sad 6 python

有些人可以帮我看看如何在python中找到代码需要多少时间和内存?

Dan*_* Li 12

用它来计算时间:

import time

time_start = time.clock()
#run your code
time_elapsed = (time.clock() - time_start)
Run Code Online (Sandbox Code Playgroud)

正如Python文档所引用的那样:

time.clock()

在Unix上,将当前处理器时间返回为以秒为单位的浮点数.精度,实际上是"处理器时间"含义的定义,取决于同名C函数的精度,但无论如何,这是用于对Python或时序算法进行基准测试的函数.

在Windows上,此函数返回自第一次调用此函数以来经过的挂钟秒,作为浮点数,基于Win32函数QueryPerformanceCounter().分辨率通常优于1微秒.

参考:http://docs.python.org/library/time.html


用它来计算内存:

import resource

resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
Run Code Online (Sandbox Code Playgroud)

参考:http://docs.python.org/library/resource.html


Wol*_*ahl 7

基于@Daniel Li对剪切和粘贴便利性和 Python 3.x 兼容性的回答:

import time
import resource 

time_start = time.perf_counter()
# insert code here ...
time_elapsed = (time.perf_counter() - time_start)
memMb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024.0/1024.0
print ("%5.1f secs %5.1f MByte" % (time_elapsed,memMb))
Run Code Online (Sandbox Code Playgroud)

例子:

 2.3 secs 140.8 MByte
Run Code Online (Sandbox Code Playgroud)