怎么样记录、统计、测量出Python程序的运行时间(用Python内置的datetime实现)

怎么样记录、统计、测量出Python程序的运行时间(用Python内置的datetime实现),第1张

可以用Python内置的datetime实现对Python程序运行时间的测量。

示例代码如下:

import cv2 as cv
import sys
import datetime

image = cv.imread('F:/material/images/2022/2022-06/01_woman_samll.jpg',0)
if image is None:
    print('Error: Could not load image')
    sys.exit()

begin1 = datetime.datetime.now()
for i in range(200):
    Canny_low = cv.Canny(image, 50, 100, apertureSize=3)
end1 = datetime.datetime.now()
# 以秒为单位
print('Canny(opencv-python) time consuming:{}s'.format((end1 - begin1).total_seconds()))
# 以毫秒为单位
print('Canny(opencv-python) time consuming:{}ms'.format(1000*((end1 - begin1).total_seconds())))
# 以微秒为单位(注意是微秒,不是毫秒,1毫秒=1000微秒)
print('Canny(opencv-python) time consuming:{}μs'.format((end1 - begin1).microseconds))

运行结果如下图所示:

注意:测试较短代码运行时间的时候最好运行成百上千次后取平均值,如果只测一次很可能会因为一些偶然因素造成时间差别很大,比如进程切换等因素。

扩展阅读:
利用C++中的函数getTickCount()和getTickFrequency()测量函数的运行时间

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1498412.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-25
下一篇 2022-06-25

发表评论

登录后才能评论

评论列表(0条)

保存