深度阅读

How to check the execution time of Python script

作者
作者
2023年08月22日
更新时间
14.44 分钟
阅读时间
0
阅读量

To check the execution time of a Python script, there are several approaches that you can take:

  1. Using the time module: You can use the time module to record the start and end time of the script and then calculate the difference between the two times. Here’s an example:
import time

start_time = time.time()

# Your Python code here

end_time = time.time()
print(f"Execution time: {end_time - start_time:.5f} seconds")

This will print the execution time of your code in seconds (with 5 decimal places).
2. Using the timeit module: The timeit module provides a simple way to time small bits of Python code. You can use it to time your script like this:

import timeit

def main():
   # Your Python code here

print(f"Execution time: {timeit.timeit(main, number=1)} seconds")

This will print the execution time of your code in seconds.
3. Using a decorator: You can create a decorator that calculates the execution time of a function. Here’s an example:

import time

def timing_decorator(func):
   def wrapper(*args, **kwargs):
       start_time = time.time()
       result = func(*args, **kwargs)
       end_time = time.time()
       print(f"Execution time: {end_time - start_time:.5f} seconds")
       return result

   return wrapper

@timing_decorator
def main():
   # Your Python code here

This will print the execution time of your code in seconds and also return the result of the function.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。