Python 计算程序运行时间的几种方法

方法1

import datetime

starttime = datetime.datetime.now()

#long running

endtime = datetime.datetime.now()

print (endtime - starttime).seconds

方法 2

start = time.time()

run_fun()

end = time.time()

print end-start

方法3

start = time.clock()

run_fun()

end = time.clock()

print end-start

方法1和方法2都包含了其他程序使用CPU的时间,是程序开始到程序结束的运行时间。

方法3算只计算了程序运行的CPU时间

### Python 程序执行时间限制的设置方法Python 中,可以通过多种方式实现对程序或函数运行时间的限制。以下是几种常见的方法及其适用场景: #### 方法一:使用 `subprocess` 库 当需要调用外部命令并对其执行时间进行限制时,推荐使用 `subprocess` 模块。通过创建子进程对象,并利用其内置的超时机制来控制执行时间。 ```python import subprocess try: # 创建子进程并指定超时时间为5秒 result = subprocess.run(['your_command', 'param'], timeout=5, check=True) except subprocess.TimeoutExpired: print("Command timed out after 5 seconds.") except subprocess.CalledProcessError as e: print(f"An error occurred: {e}") ``` 此方法适用于对外部命令的执行时间进行管理[^1]。 --- #### 方法二:使用第三方库 `func_timeout` 对于普通的 Python 函数,可以借助 `func_timeout` 第三方库来限制其执行时间。这种方法简单易用,适合快速开发需求。 安装依赖: ```bash pip install func-timeout ``` 代码示例: ```python from func_timeout import func_set_timeout, FunctionTimedOut import time @func_set_timeout(2.1) # 设置最大执行时间为2.1秒 def long_running_function(): while True: print('Running...') time.sleep(1) try: long_running_function() except FunctionTimedOut: print("Function execution exceeded the allowed time limit of 2.1 seconds.") ``` 上述代码展示了如何定义一个带有时间限制的函数,并捕获可能抛出的超时异常[^2]。 --- #### 方法三:手动实现基于线程的时间限制 如果不希望引入额外的依赖项,则可通过多线程技术自行实现时间限制功能。这种方式更加灵活,但也相对复杂一些。 代码示例: ```python import threading class TimeoutException(Exception): pass def run_with_timeout(func, args=(), kwargs=None, timeout_duration=2.1): if kwargs is None: kwargs = {} class InterruptableThread(threading.Thread): def __init__(self): super().__init__() self.result = None def run(self): try: self.result = func(*args, **kwargs) except Exception as e: raise e it = InterruptableThread() it.start() it.join(timeout_duration) if it.is_alive(): raise TimeoutException(f"Execution took longer than {timeout_duration} seconds.") else: return it.result # 测试函数 def test_function(): import time time.sleep(3) return "Finished" try: res = run_with_timeout(test_function, timeout_duration=2.1) print(res) except TimeoutException as te: print(te) ``` 这段代码实现了自定义的时间限制逻辑,支持任意可调用的对象作为目标函数。 --- #### 总结 以上三种方案分别针对不同场景提供了有效的解决办法。如果仅需处理简单的外部命令调用,建议优先选用 `subprocess`;而对于内部函数的时间约束,可以选择更便捷的 `func_timeout` 或更具灵活性的手动线程实现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值