python - 使用ctypes和SSE/AVX SOMETIMES段错误

toe*_*ebs 3 python ctypes sse segmentation-fault avx

+我正在尝试使用AVX优化一段python代码.我正在使用ctypes来访问C++函数.有时功能会发生故障,有时甚至不会.我认为它可能与对齐有关?也许任何人都可以帮助我,我有点被困在这里.

Python的代码:

from ctypes import *
import numpy as np
#path_cnt
path_cnt = 16
c_path_cnt = c_int(path_cnt)

#ndarray1
ndarray1      = np.ones(path_cnt,dtype=np.float32,order='C')
ndarray1.setflags(align=1,write=1)
c_ndarray1     = stock.ctypes.data_as(POINTER(c_float))

#ndarray2
ndarray2    = np.ones(path_cnt,dtype=np.float32,order='C');
ndarray2.setflags(align=1,write=1)
c_ndarray2  = max_vola.ctypes.data_as(POINTER(c_float))

#call function
finance = cdll.LoadLibrary(".../libfin.so")
finance.foobar.argtypes = [c_void_p, c_void_p,c_int]
finance.foobar(c_ndarray1,c_ndarray2,c_path_cnt)
x=0
while x < path_cnt:   
    print  c_stock[x]
    x+=1
Run Code Online (Sandbox Code Playgroud)

C++代码

extern "C"{
int foobar(float * ndarray1,float * ndarray2,int path_cnt)
 {
     for(int i=0;i<path_cnt;i=i+8)
     {
         __m256 arr1                = _mm256_load_ps(&ndarray1[i]);
         __m256 arr2                    = _mm256_load_ps(&ndarray2[i]);
         __m256 add                 = _mm256_add_ps(arr1,arr2);
         _mm256_store_ps(&ndarray1[i],add);
     }
     return 0;
 }
}
Run Code Online (Sandbox Code Playgroud)

而现在奇怪的输出行为,使得终端中的一些调用两次给出不同的结果!

tobias@tobias-Lenovo-U310:~/workspace/finance$ python finance.py 
Segmentation fault (core dumped)
tobias@tobias-Lenovo-U310:~/workspace/finance$ python finance.py 
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Ben*_*son 6

有对齐和未对齐的加载指令.如果违反对齐规则,对齐的将会出错,但速度更快.未对齐的接受任何地址并在内部执行加载/移位以获取所需的数据.您正在使用对齐版本,_mm256_load_ps并且可以在_mm256_loadu_ps没有任何中间分配的情况下切换到未对齐版本.

一个好的矢量化编译器将包括一个引入循环以达到一个对齐的地址,然后是一个主体来处理对齐的数据,然后是一个最后的循环来清理任何一个straggler.

  • 好答案.一些注意事项:对于最近的(Nehalem和之后的)Intel x86架构,128位未对齐负载的运行速度与对齐负载相同.对齐加载指令(MOVPS)相对于其未对齐对应(MOVUPS)的一个小优点是对齐指令具有短一个字节的编码.在某些对指令高速缓存大小敏感的情况下,这可能会产生很小的性能提升.然而,在当代架构中,256位访问对齐更敏感(尽管Haswell可能已经改进了). (2认同)