Python + Cython 두번째 

 

정리. 수알치 오상문 

 

https://www.youtube.com/watch?v=Ic1oE6SEOBs 

 

아래 내용은 유튜브 강좌의 내용과 테스트 결과를 정리한 것입니다.

 

1. cython, setuptools 설치

pip install cython      <-- 파이썬 기본 버전 이용 시 

pip install setuptools


pip3.9 install cython   <-- 파이썬 특정 버전 이용 시 
pip3.9 install setuptools

 

2.main.pyx 작성 


이 파일에는 cython 문법으로 작성된 prime_opt() 함수와 일반 파이썬 문법으로 작성된 prime() 함수가 있습니다. 
나중에 이 두 함수를 호출해서 속도를 비교할 예정입니다.

def prime(amount):
    primes = []
    found = 0
    number = 2
    while found < amount:
        for x in primes:
            if number % x == 0:
                break
        else:
            primes.append(number)
            found += 1
        number += 1
    return primes

def prime_opt(in amount):
    cdef int number, x, founf
    cdef int primes[100000]

    amount = min(amount, 100000)
    found = 0
    number = 2

    while found < amount:
        for x in primes[:found]:
            if number % x == 0:
                break
        else:
            primes[found] = number
            found += 1
        number += 1

    return_list = [p for p in primes[:found]]
    return return_list

 

3. setup.py 작성 


cython 빌드를 위한 설정 파일입니다.

from setuptools import setup
from Cython.Build import cuthonize

setup(
    ext_modules=cythonize('main.pyx')
)

 

4. Cython 빌드 실행

 

 커맨드라인에서 명령을 입력합니다.

python setup.py build_ext --inplace

그러면 아래 과정처럼 main.pyx를 c 파일로 변경하고 gcc로 컴파일하여 공유 라이브러리 파일을 생성합니다.

Compiling main.pyx because it changed.
[1/1] Cythonizing main.pyx
/usr/local/lib/python3.9/site-packages/Cython/Compiler/Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /root/main.pyx
  tree = Parsing.p_module(s, pxd, full_module_name)
running build_ext
building 'main' extension
creating build
creating build/temp.linux-x86_64-3.9
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/usr/local/include/python3.9 -c main.c -o build/temp.linux-x86_64-3.9/main.o
creating build/lib.linux-x86_64-3.9
gcc -pthread -shared build/temp.linux-x86_64-3.9/main.o -o build/lib.linux-x86_64-3.9/main.cpython-39-x86_64-linux-gnu.so
copying build/lib.linux-x86_64-3.9/main.cpython-39-x86_64-linux-gnu.so ->

중간에 main.c라는 파일 만들어지고 gcc를 이용하여 컴파일 공유 라이브러리 파일로 만들어집니다. 
참고로 main.c는 이런 구조입니다.


/* Generated by Cython 3.0.3 */
/* BEGIN: Cython Metadata
{
    "distutils": {
        "name": "main",
        "sources": [
            "main.pyx"
        ]
    },
    "module_name": "main"
}
END: Cython Metadata */

#ifndef PY_SSIZE_T_CLEAN
#define PY_SSIZE_T_CLEAN
이하 생략...

 

5. test.py 작성

import main
import time

start1 = time.time()
main.prime_opt(30000)
end1 = time.time()
print(end1 - start1)

start2 = time.time()
main.prime(30000)
end2 = time.time()
print(end2 - start2)

 

6. 테스트 진행


python test.py

만든 라이브러리의 두 함수를 호출하여 속도 차이를 확인합니다. 

0.6637105941772461  <-- C 방식의 함수 실행 시간
6.353474140167236   <-- 파이썬 방식 함수 실행 시간

 

 

반응형

+ Recent posts