如何测量cython的运行时间并与python代码进行比较?

5n0oy7gb  于 2023-02-17  发布在  Python
关注(0)|答案(1)|浏览(123)

我使用time.time来测量pyx文件内部并打印它来检查时间,但我认为它的运行时间不正确,它显示了相同代码行的不同时间,并且每次运行的时间都在变化,它还显示了每个for循环的不同时间,但所有循环都在做相同的工作,0.010和0.020,有时该部分显示0,而其他3个部分显示0.010和0.020。请帮助我如何正确测量它,在cython文档中找不到任何测量时间的好方法
对于这部分代码,它显示了这两次,并且在每次运行中有时会发生变化:

t4 = time.time()
    # print('T3 =', t4 - t3)
    for j in range(np.shape(im1)[1]):
        # sum_c1[j] = np.shape(im1)[0] - (np.sum(im1[:, j]))
        sum_c1[j] = np.shape(im1)[0] - (np.count_nonzero(im1[:, j]))
    tt3 = time.time()
    print('TT3 =', tt3 - t4)
    cdef int amc1 = np.argmax(sum_c1)  # argmax sum_c1
    tt4 = time.time()
    # print('TT4 =', tt4 - tt3)
    for j in range(np.shape(im2)[1]):
        # sum_c2[j] = np.shape(im2)[0] - (np.sum(im2[:, j]))
        sum_c2[j] = np.shape(im2)[0] - (np.count_nonzero(im2[:, j]))
    t5 = time.time()
    print('TT5 =', t5 - tt4)
    # print('T4 =', t5 - t4)
    ## find of max zeros in row
    for j in range(np.shape(im1)[0]):
        # sum_r1[j] = np.shape(im1)[1] - (np.sum(im1[j, :]))
        sum_r1[j] = np.shape(im1)[1] - (np.count_nonzero(im1[j, :]))
    tt1 = time.time()
    print('TT1 =', tt1 - t5)
    cdef int amr1 = np.argmax(sum_r1)  # argmax sum_r1
    tt2 = time.time()
    # print('TT2 =', tt2 - tt1)
    for j in range(np.shape(im2)[0]):
        # sum_r2[j] = np.shape(im2)[1] - (np.sum(im2[j, :]))
        sum_r2[j] = np.shape(im2)[1] - (np.count_nonzero(im2[j, :]))
    t6 = time.time()
    print('T5 =', t6 - t5)
('TT3 =', 0.020589590072631836)
('TT5 =', 0.011527061462402344)
('TT1 =', 0.0)
('T5 =', 0.009999990463256836)

-----------
('TT3 =', 0.0100250244140625)
('TT5 =', 0.00996851921081543)
('TT1 =', 0.01003265380859375)
('T5 =', 0.020001888275146484)

这是同一代码上的2次不同运行

sy5wg1nm

sy5wg1nm1#

那么使用perf_counter()呢?

start = time.perf_counter()
# your code
print(time.perf_counter()-start)

更多详情请点击此处:https://stackoverflow.com/a/52228375/3872144

相关问题