python - 如何计算 Python 程序运行的时间?

标签 python time

是否有一种简单的方法来为 Python 程序的执行计时?

澄清:整个程序

最佳答案

使用timeit :

This module provides a simple way to time small bits of Python code. It has both command line as well as callable interfaces. It avoids a number of common traps for measuring execution times.

你需要一个字符串中的 python 语句;如果你的代码中有一个 main 函数,你可以像这样使用它:

>>> from timeit import Timer
>>> timer = Timer('main()', 'from yourmodule import main')
>>> print timer.timeit()

第二个字符串提供设置,第一个语句要计时的环境。第二部分不计时,旨在照原样设置舞台。然后第一个字符串贯穿它的步伐;默认情况下一百万次,以获得准确的时间。

如果您需要有关速度较慢的更多详细信息,请使用 python profilers 之一:

A profiler is a program that describes the run time performance of a program, providing a variety of statistics.

最简单的运行方法是在命令行中使用 cProfile 模块:

$ python -m cProfile yourprogram.py

关于python - 如何计算 Python 程序运行的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10883387/

相关文章:

python - 我将如何使用 django.forms 使用模型中的行预填充选择字段?

scala - 如何将此 "Wed, 10 Jun 2020 10:16:24 GMT"转换为此 "2020-05-10T12:30:45"datetimestr 格式

javascript - momentJS 知道时区转换后的前一天、当前或后一天

java - 如何解析来自计时器(android)的值?

c++ - 在 Howard Hinnant 的 Date 库中获取毫秒舍入时间戳字符串的最佳方法是什么?

Javascript 检查特定时间并返回 UTC 时区

python - 满足条件时停止应用

python - 内部列表中的第一项尽可能高效

python - Python批量查询结果分组

python - 计算python中范围内列表中的 float 数量