我在c中实现了一个python扩展,发现在python中执行c函数比从c main执行c代码快两倍。
但为什么这么快?我希望当从python调用时,纯c的性能与从c调用时完全相同。
这是我的实验:
普通C计算代码(矩阵乘法的简单3)
调用mmult()函数的纯C主函数
调用mmult()函数的python扩展包装器
所有的计时都完全在C代码中进行
以下是我的结果:
纯C-85US
python扩展-36us
这是我的代码:
--结果cpp----
#include "mmult.h"
void mmult(int32_t a[1024],int32_t b[1024],int32_t c[1024]) {
struct timeval t1, t2;
gettimeofday(&t1, NULL);
for(int i=0; i<32; i=i+1) {
for(int j=0; j<32; j=j+1) {
int32_t result=0;
for(int k=0; k<32; k=k+1) {
result+=a[i*32+k]*b[k*32+j];
}
c[i*32+j] = result;
}
}
gettimeofday(&t2, NULL);
double elapsedTime = (t2.tv_usec - t1.tv_usec) + (t2.tv_sec - t1.tv_sec)*1000000;
printf("elapsed time: %fus\n",elapsedTime);
}
--结果H-------
#include <stdint.h>
void mmult(int32_t a[1024],int32_t b[1024],int32_t c[1024]);
--主CPP------
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "mmult.h"
int main() {
int* a = (int*)malloc(sizeof(int)*1024);
int* b = (int*)malloc(sizeof(int)*1024);
int* c = (int*)malloc(sizeof(int)*1024);
for(int i=0; i<1024; i++) {
a[i]=i+1;
b[i]=i+1;
c[i]=0;
}
struct timeval t1, t2;
gettimeofday(&t1, NULL);
mmult(a,b,c);
gettimeofday(&t2, NULL);
double elapsedTime = (t2.tv_usec - t1.tv_usec) + (t2.tv_sec - t1.tv_sec)*1000000;
printf("elapsed time: %fus\n",elapsedTime);
free(a);
free(b);
free(c);
return 0;
}
以下是我如何编译main:
gcc -o main main.cpp mmult.cpp -O3
--包装器.cpp-----
#include <Python.h>
#include <numpy/arrayobject.h>
#include "mmult.h"
static PyObject* mmult_wrapper(PyObject* self, PyObject* args) {
int32_t* a;
PyArrayObject* a_obj = NULL;
int32_t* b;
PyArrayObject* b_obj = NULL;
int32_t* c;
PyArrayObject* c_obj = NULL;
int res = PyArg_ParseTuple(args, "OOO", &a_obj, &b_obj, &c_obj);
if (!res)
return NULL;
a = (int32_t*) PyArray_DATA(a_obj);
b = (int32_t*) PyArray_DATA(b_obj);
c = (int32_t*) PyArray_DATA(c_obj);
/* call function */
mmult(a,b,c);
Py_RETURN_NONE;
}
/* define functions in module */
static PyMethodDef TheMethods[] = {
{"mmult_wrapper", mmult_wrapper, METH_VARARGS, "your c function"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef cModPyDem = {
PyModuleDef_HEAD_INIT,
"mmult", "Some documentation",
-1,
TheMethods
};
PyMODINIT_FUNC
PyInit_c_module(void) {
PyObject* retval = PyModule_Create(&cModPyDem);
import_array();
return retval;
}
--安装程序.py-----
import os
import numpy
from distutils.core import setup, Extension
cur = os.path.dirname(os.path.realpath(__file__))
c_module = Extension("c_module", sources=["wrapper.cpp","mmult.cpp"],include_dirs=[cur,numpy.get_include()])
setup(ext_modules=[c_module])
--代码.py-----
import c_module
import time
import numpy as np
if __name__ == "__main__":
a = np.ndarray((32,32),dtype='int32',buffer=np.linspace(1,1024,1024,dtype='int32').reshape(32,32))
b = np.ndarray((32,32),dtype='int32',buffer=np.linspace(1,1024,1024,dtype='int32').reshape(32,32))
c = np.ndarray((32,32),dtype='int32',buffer=np.zeros((32,32),dtype='int32'))
c_module.mmult_wrapper(a,b,c)
下面是我如何编译python扩展:
python3.6 setup_sw.py build_ext --inplace
更新
我更新了mmult.cpp代码,以便在内部运行3for 1000000次迭代。这导致了非常相似的情况:
纯C-27US
python扩展-27us
最佳答案
85微秒的延迟太小,无法可靠地重复测量。例如,CPU cache效果(或context switches或paging)可能支配计算时间(并改变它使该计时无意义)。
(我想您使用的是linux/x86-64)
根据经验,试着让跑步至少持续半秒,并重复基准测试几次。您也可以使用time(1)进行测量。
另请参见time(7)。时间有几个概念(经过的“实时”时间、单调时间、进程CPU时间、线程CPU时间等)。您可以考虑使用clock(3)或clock_gettime(2)来测量时间。
顺便说一句,您可以使用较新版本的GCC(2017年11月,GCC7和几周后的gcc8)编译,并且您希望使用gcc -march=native -O3
编译以进行基准测试。也可以尝试其他optimization options和调谐。您也可以尝试其他编译器,例如Clang/LLVM。
还要看this对相关问题的回答(关于并行化)。可能numpy包正在使用(内部)类似的技术(在Python GIL之外),因此可能比c中的简单顺序矩阵乘法代码快。