Python 如何检查脚本的执行时间

Python 如何检查脚本的执行时间

Python脚本是一个文件,可以存储用于执行特定任务或一组任务的代码。这个文件保存的文件扩展名为 “.py” 。Python脚本可以在任何文本编辑器中创建和编辑,并可以使用命令行提示符执行,也可以作为包或模块导入集成开发环境(IDE)。

每个Python脚本都需要一定的时间来执行文件;可以通过以下方式计算:

使用time模块

在Python中,我们有一个用于测量代码块执行时间的time模块。time模块的 time() 函数返回以秒为单位的时间,然后计算开始时间和结束时间的差来获取给定代码块的执行时间。

示例

在这个例子中,我们将创建Python脚本,并使用time模块的 time() 函数检查执行时间。

在代码中,我们将创建Python脚本并将脚本导入Python环境,然后计算脚本的执行时间。

import python_sample as ps
import time
start_time = time.time()
script = ps.python_script("Welcome to Tutorialspoint")
print(script)
end_time = time.time()
execution_time = start_time - end_time
print("Execution time:",execution_time)

输出

给定的Python脚本的执行时间如下:

Welcome to Tutorialspoint
Execution time: -0.0009975433349609375

示例

让我们看另一个使用时间模块计算执行时间的示例 time() 函数。

import python_sample as ps
import time
start_time = time.time()
statement = "Python is the most popular programming language"
print(statement)
end_time = time.time()
execution_time = start_time - end_time
print("Execution time:",execution_time)

输出

给定Python代码片段的执行时间如下。

Python is the most popular programming language
Execution time: -0.0009970664978027344

使用timeit模块

timeit是另一个提供更精确的方法来测量代码片段执行时间的模块,它通过多次运行代码并计算所有时间结果的平均值来实现。

timeit模块提供了timeit函数,它将脚本作为输入并计算执行时间;它返回以秒为单位的格式。

示例

以下是计算Python脚本执行时间的示例。

import python_sample as ps
import timeit
script = ps.python_script("Welcome to Tutorialspoint,Have a happy learning")
print(script)
execution_time = timeit.timeit(number = 50)
print("Execution time:",execution_time)

输出

以下是使用timeit模块的timeit函数计算的Python脚本执行时间的输出。

Welcome to Tutorialspoint,Have a happy learning
Execution time: 1.100008375942707e-06

使用cProfile模块函数

在Python中,还有另一个可用的模块,它可以找到Python脚本的执行时间。cProfile具有函数,该函数计算每个函数执行的时间以及整个Python脚本的执行时间。

示例

以下是使用模块的函数计算执行时间的示例。

import cProfile
cProfile.run('python_sample')

输出

3 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

示例

让我们再看一个例子,使用cProfile模块计算Python脚本的执行时间,使用 run() 函数。

import cProfile
import sample
cProfile.run('sample')

输出

以下是以上代码的输出。

  3 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :1()
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程