반응형
반응형

https://docs.microsoft.com/ko-kr/visualstudio/python/working-with-c-cpp-python-in-visual-studio?view=vs-2019

 

Python용 C++ 확장명 작성 - Visual Studio

혼합 모드 디버깅을 비롯하여 Visual Studio, CPython 및 PyBind11을 사용하여 Python에 대한 C++ 확장을 만드는 연습 과정입니다.

docs.microsoft.com

위의 글 중 CPython 확장을 활용하여 Wrapping 구현 및 성능 확인을 하였다.

 

먼저 Wrapping할 C++ 코드를 작성한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//modul.cpp
#include <Windows.h>
#include <cmath>
#include <Python.h>
const double e = 2.7182818284590452353602874713527;
 
double sinh_impl(double x) {
    return (1 - pow(e, (-2 * x))) / (2 * pow(e, -x));
}
 
double cosh_impl(double x) {
    return (1 + pow(e, (-2 * x))) / (2 * pow(e, -x));
}
 
PyObject* tanh_impl(PyObject *, PyObject* o) {
    double x = PyFloat_AsDouble(o);
    double tanh_x = sinh_impl(x) / cosh_impl(x);
    return PyFloat_FromDouble(tanh_x);
}
 
static PyMethodDef superfastcode_methods[] = {
    // The first property is the name exposed to Python, fast_tanh, the second is the C++
    // function name that contains the implementation.
    { "fast_tanh", (PyCFunction)tanh_impl, METH_O, nullptr },
 
    // Terminate the array with an object containing nulls.
    { nullptr, nullptr, 0, nullptr }
};
 
static PyModuleDef superfastcode_module = {
    PyModuleDef_HEAD_INIT,
    "superfastcode",                        // Module name to use with Python import statements
    "Provides some functions, but faster",  // Module description
    0,
    superfastcode_methods                   // Structure that defines the methods of the module
};
 
PyMODINIT_FUNC PyInit_superfastcode() {
    return PyModule_Create(&superfastcode_module);
}
cs

 

C++ code를 Build 하기 위해 아래와 같은 Python code를 작성한다.

1
2
3
4
5
6
7
8
9
#setup.py
from distutils.core import setup, Extension, DEBUG
 
sfc_module = Extension('superfastcode', sources = ['module.cpp'])
 
setup(name = 'superfastcode', version = '1.0',
    description = 'Python Package with superfastcode C++ extension',
    ext_modules = [sfc_module]
    )
cs

 

c++ 파일과 setup.h을 같은 폴더 경로에 두고, 콘솔창을 열어 해당 폴더로 이동 후 아래와 같이 명령어를 실행한다.

pip intall .

이미지와 같이 빌드가 되는 것을 확인 할 수 있다.

 

새로운 Python 파일을 만들어, 성능을 테스트 해보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
from superfastcode import fast_tanh
import numpy as np
import time
 
# C++ 로 Wrapping한 tanh 함수를 이용해 속도 측정
start = time.time()
result = list([fast_tanh(i) for i in range(10000000)])
print(time.time()-start
 
# Python numpy에서 제공하는 tanh 함수를 이용해 속도 측정
start = time.time()
result = list([np.tanh(i) for i in range(10000000)])
print(time.time()-start)
cs

 

실험 결과 C++ Wrapping 한 tanh 함수는 2.41 초가 걸린 반면, numpy의 tanh 함수는 7.31초가 걸리는 것을 확인하였다.

반응형

+ Recent posts

반응형