Cython因打印而减速

时间:2017-08-23 17:07:59

标签: python python-3.x numpy cython

在对我的一些代码进行cython化之前,我正在做一些测试,就我而言,我已经产生了一些奇怪的行为。

浏览网页我偶然发现了一个链接,该链接表示cython中的C-Like操作比numpy函数更快,我觉得这很奇怪,所以我决定测试它。

我使用的代码是:

cimport cython

import numpy as np
cimport numpy as np

import time


@cython.boundscheck(False)
@cython.wraparound(False)

def main():
    # Test #1

    n = 100000000
    x = np.random.rand(n)

    start_time = time.time()

    s = x.sum()


    print("--- FINAL: {sec:1.5f} seconds ---".format(sec = time.time() - start_time))


    print(s)


    #Test #2

    cdef int n2 = 100000000

    cdef np.ndarray x2 = np.empty(n2, dtype = np.double)

    x2 = np.random.rand(n2)

    #x =

    start_time = time.time()

    s2 = x2.sum()


    print("--- FINAL: {sec:1.5f} seconds ---".format(sec = time.time() - start_time))


    print(s2)



    #Test #3
    cdef int n3 = n2
    cdef int i
    cdef double s3 = 0

    cdef np.ndarray x3 = np.empty(n3, dtype = np.double)

    x3 = np.random.rand(n3)


    cdef double [:] x3_view = x3




    start_time = time.time()

    for i in range(n3):
        s3 += x3_view[i]


    print("--- FINAL: {sec:1.10f} seconds ---".format(sec = time.time() - start_time))

    print(s3) # THIS LINE

奇怪的部分是:

当我运行代码时,我得到:

--- FINAL: 0.12800 seconds ---
--- FINAL: 0.13792 seconds ---
--- FINAL: 0.1550407410 seconds ---

但是当我评论最后一行,# THIS LINE指示的那一行时,我得到:

--- FINAL: 0.13035 seconds ---
--- FINAL: 0.14981 seconds ---
--- FINAL: 0.0000000000 seconds ---

非常奇怪的部分是我所引用的print语句甚至没有被start_timeprint seconds语句括起来。

有关正在发生的事情的任何线索?

1 个答案:

答案 0 :(得分:3)

Cython编译为C,然后C编译器优化结果。当你实际上没有使用s3时,C编译器可以自由地完全删除计算s3的循环,因为循环的唯一影响是缓慢的。