Python 如何在 PyCharm 中计算脚本执行时间而不每次都添加代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35656239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I time script execution time in PyCharm without adding code every time?
提问by KarolisR
Currently I just add the following lines around my code:
目前我只是在我的代码周围添加以下几行:
import time
start_time = time.time()
# my code here
print "time elapsed: {:.2f}s".format(time.time() - start_time)
Is it possible to achieve the same without adding code to every script I want to time? Either adding something in run configuration or using a plugin?
是否可以在不向我想要计时的每个脚本中添加代码的情况下实现相同的目标?在运行配置中添加一些东西还是使用插件?
采纳答案by lev
You can profile your script by hitting the 'profile' button (it is to the right of the 'run', 'debug', and 'run with coverage' buttons):
您可以通过点击“配置文件”按钮来配置您的脚本(它位于“运行”、“调试”和“运行覆盖”按钮的右侧):
Among the output, you will find the name of the script itself, and the time needed to run it.
在输出中,您将找到脚本本身的名称以及运行它所需的时间。
Note: the function is available in PyCharm PROFESSIONAL 2017.1 for the Linux platform; other installations might not provide the profiler button.
注:该函数在Linux平台的PyCharm PROFESSIONAL 2017.1中可用;其他安装可能不提供分析器按钮。
回答by Vedant Kandoi
I know it is late but I wanted the same thing and here is what I did:
我知道已经晚了,但我想要同样的东西,这就是我所做的:
Create another python file in the directory of your codes:
在代码目录中创建另一个 python 文件:
import time
st=time.time()
import test
print("----%.2f----"%(time.time()-st))
where test is your program name. So if you want to run any program just run it from here by just changing test.
其中 test 是您的程序名称。因此,如果您想运行任何程序,只需更改 test 即可从这里运行它。
Keep in mind that import runs the code normally if you haven't used:
请记住,如果您没有使用过 import 会正常运行代码:
if __name__=="__main__":
回答by YvesgereY
Just write corresponding unit test (works with community edition).
只需编写相应的单元测试(适用于社区版)。
from unittest import TestCase
from yourscript import yourcode
class TestSol(TestCase):
def benchmark(self):
res = yourcode('banana')
self.assertEqual(res, 77)
PyCharm neatly displays time taken for each test.
PyCharm 整齐地显示每次测试所用的时间。
Another solution would be to wrap the interpreter with time
.
But since it will help in other ways, I recommend taking the unit-tests road.
另一种解决方案是用time
.
但由于它会在其他方面有所帮助,我建议走单元测试之路。