我想优化Python函数的执行时间,该函数大量使用了内置的datetime
实用程序。我的功能正常,但速度很慢
# Check if an ending date (stored in a YYYY-MM-DD string) is
# within range of a beginning date (in the same format). Two
# numbers, the min/max length, define how soon/distant the 2nd
# date can be from the 1st.
minDelayLength = 1
maxDelayLength = 999
def checkDateRange(dateStr1, dateStr2):
date1 = datetime.strptime(dateStr1, '%Y-%m-%d')
date2 = datetime.strptime(dateStr2, '%Y-%m-%d')
minLimit = date1 + timedelta(days=minDelayLength)
maxLimit = date1 + timedelta(days=maxDelayLength)
return minLimit <= date2 <= maxLimit
在我的计算机上运行1000000个这个函数的调用大约需要40秒,因此我使用cProfile
分析了一次函数的运行以查找性能问题。我发现它会进行大量的函数调用:
2634 function calls (2548 primitive calls) in 0.050 seconds
有人对如何改进我的工作有什么建议吗?我可以假设函数的输入总是有效的(格式正确),并且我可以假设最小/最大长度不会改变
代码中最慢的部分是
strptime
。如果您确定日期字符串的格式总是YYYY-MM-DD
,那么您可以使用下面的方法,该方法使其速度提高了11倍(在500000次调用中进行了测试)相关问题 更多 >
编程相关推荐