如何用Python实现程序运行每秒1美分的计费功能?
解决方案
你可以基于现有代码,通过以下简单修改实现计费功能:
- 提取程序运行的总秒数
- 按每秒1美分的规则计算费用
- 格式化输出指定内容
修改后的完整代码:
from datetime import datetime start_time = datetime.now() # 这里是你的业务代码 # my code end_time = datetime.now() # 计算运行时长(取整数秒) duration_seconds = int((end_time - start_time).total_seconds()) # 计算对应费用 cost_cents = duration_seconds * 1 # 按要求格式输出结果 print(f"您的程序已运行{duration_seconds}秒,需支付{cost_cents}美分")
可选调整
- 如果要对不足1秒的运行时间也按1秒计费(比如运行10.2秒按11秒算),可以用向上取整:
import math duration_seconds = math.ceil((end_time - start_time).total_seconds()) - 如果需要保留精确的小数时长(比如运行10.5秒收10.5美分),可以直接使用原始秒数输出:
duration_seconds = (end_time - start_time).total_seconds() cost_cents = duration_seconds * 1 print(f"您的程序已运行{duration_seconds:.1f}秒,需支付{cost_cents:.1f}美分")
内容的提问来源于stack exchange,提问作者venus
相关产品推荐
相关产品推荐

