Skip to content

Instantly share code, notes, and snippets.

@mcchae
Last active August 29, 2015 14:14
Show Gist options
  • Save mcchae/728268a7b298886a2332 to your computer and use it in GitHub Desktop.
Save mcchae/728268a7b298886a2332 to your computer and use it in GitHub Desktop.
from ctypes import *
import os
mylib = cdll.LoadLibrary('%s/loopcheck.so' % os.getcwd())
res = mylib.loop(100000, 10000)
#include <stdio.h>
void loop(int len1, int len2) {
int i, j;
for(i=0; i<len1; i++) {
for(j=0; j<len2; j++) {
if(i==len1-1 && j==len2-1)
printf("Loop End!!\n");
}
}
}
def loop(len1, len2):
for i in xrange(len1):
for j in xrange(len2):
if i == (len1-1) and j == (len2-1):
print "End For Loop!"
loop(100000, 10000)
import time
def loop(int len1, int len2):
for i in range(len1):
for j in xrange(len2):
if i == (len1-1) and j == (len2-1):
print "End For Loop!"
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'loop',
ext_modules = cythonize("loopcheck.pyx"),
)
@joonro
Copy link

joonro commented Jan 29, 2015

Cython은 모든 변수들의 Type을 지정해주고, 특히 loop 안에서 Python call이 없어야 제 속도가 납니다. 다음 예를 비교하면 (1000, 1000) 기준으로 했을 때 속도가 20.8 ms per loop VS 316 µs per loop으로 빨라집니다.

loopcheck without type declaration: (loopcheck.pyx)

def loop(int len1, int len2):
    return_val = 0
    for i in range(len1):
        for j in xrange(len2):
            if i == (len1-1) and j == (len2-1):
                return_val += i
                return_val -= i

    return(return_val)

loopcheck with type declaration: (loopcheck_typed.pyx)

def loop(int len1, int len2):

    cdef:
        int i, j
        int return_val = 0

    for i in range(len1):
        for j in xrange(len2):
            if i == (len1 - 1) and j == (len2 - 1):
                return_val += i
                return_val -= i

    return(return_val)

setup.py for loopcheck_typed.pyx:

from distutils.core import setup
from Cython.Build import cythonize
setup(
  name = 'loop_typed',
  ext_modules = cythonize("loopcheck_typed.pyx"),
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment