Cython:为什么size_t比int快? [英] Cython: why is size_t faster than int?
问题描述
将某些Cython变量从 int
类型更改为 size_t
类型可以显着减少某些功能时间(约30%),但是我不明白为什么.
Changing certain Cython variables from type int
to type size_t
can significantly reduce some functions times (~30%), but I do not understand why.
例如:
cimport numpy as cnp
import numpy as np
def sum_int(cnp.int64_t[::1] A):
cdef unsigned long s = 0
cdef int k
for k in xrange(A.shape[0]):
s += A[k]
return s
def sum_size_t(cnp.int64_t[::1] A):
cdef unsigned long s = 0
cdef size_t k
for k in xrange(A.shape[0]):
s += A[k]
return s
a = np.array(range(1000000))
计时结果:
In [17]: %timeit sum_int(a)
1000 loops, best of 3: 652 µs per loop
In [18]: %timeit sum_size_t(a)
1000 loops, best of 3: 427 µs per loop
我是Cython的新手,对Fortran的了解比对C的了解还多.请帮帮我.导致这种性能差异的这两个变量类型之间的重要区别是什么?我不喜欢Cython是什么?
I am new to Cython, and know Fortran better than C. Help me out. What is the important difference between these two variable types that causes such a performance difference? What is it that I don't grok about Cython?
推荐答案
您可能必须逐行进行概要分析才能找出确切的位置,但是从生成的C文件中我有一件很突出的事情:检查int
版本是否可以换成负数,假定 size_t
没问题.
You'd likely have to do a line by line profiling to find out exactly, but one thing stands out to me from the produced C file: int
version is checked for wraparound to negative numbers, size_t
is assumed ok.
在int循环中:( t_3
是从 k
分配的,它们是同一类型)
In the int loop: (t_3
is assigned from k
, they're the same type)
if (__pyx_t_3 < 0) {
__pyx_t_3 += __pyx_v_A.shape[0];
if (unlikely(__pyx_t_3 < 0)) __pyx_t_4 = 0;
} else if (unlikely(__pyx_t_3 >= __pyx_v_A.shape[0])) __pyx_t_4 = 0;
在size_t循环中:
In the size_t loop:
if (unlikely(__pyx_t_3 >= (size_t)__pyx_v_A.shape[0])) __pyx_t_4 = 0;
因此不需要环绕测试,因为 size_t
是未签名的,并且保证在索引内存中的项目时不会环绕.其余的几乎相同.
So no wraparound test is needed because size_t
is unsigned and guaranteed not to wrap around when indexing items in memory. The rest is virtually the same.
更新:关于您的 unsigned int
结果-您的int和size_t大小是多少?它们大小不同是否有可能导致更改?在我的情况下,uint和size_t的C代码是相同的.(因为size_t是未签名的,并且在此系统上特别是unsigned int)
Update: regarding your unsigned int
results - what's your size of int and size_t? Any chance they're different size, causing the change? In my case the C code for uint and size_t is identical. (since size_t is unsigned and specifically unsigned int on this system)
这篇关于Cython:为什么size_t比int快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!