Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added cython_pkg/__init__.py
Empty file.
2,976 changes: 2,976 additions & 0 deletions cython_pkg/cython_fibo.c

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions cython_pkg/cython_fibo.pyx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def cython_fibo(n):
"""Fibonacci on Cython"""
i = 0
a, b = 0, 1
if n < 2:
return [a, b][n]
while i < n:
a, b = b, a + b
i += 1
return a
8 changes: 8 additions & 0 deletions cython_pkg/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from Cython.Build import cythonize
from distutils.core import setup

setup(
ext_modules=cythonize("cython_fibo.pyx")
)

# Run command: python setup.py build_ext --inplace
39 changes: 39 additions & 0 deletions hw11.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""HW11. Fibonacci"""

from time import time

from cython_pkg.cython_pkg.cython_fibo import cython_fibo
from ext_fibo import ext_fibo


def calc_time(func, n):
start = time()
result = func(n)
print("Time: {}".format((time() - start) * 10 ** 3))

return result


def python_fib(n):
"""Fibonacci on Python"""
i = 0
a, b = 0, 1
if n < 2:
return n
while i < n:
a, b = b, a + b
i += 1
return a


if __name__ == '__main__':
N = 40

print("Python")
print(calc_time(python_fib, N))

print("\nCython")
print(calc_time(cython_fibo, N))

print("\nExtension")
print(calc_time(ext_fibo, N))
Empty file added python_ext/__init__.py
Empty file.
35 changes: 35 additions & 0 deletions python_ext/ext_fibo.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include <Python.h>

static PyObject* ext_fibo(PyObject* self, PyObject *args){
int n;
int i = 0;
int a = 0, b = 1, c = 0;

PyArg_ParseTuple(args, "I", &n);

if (n < 2){
return PyLong_FromLong(n);
}

while(i < n){
c=a;
a=b; b=c+b;
i++;
}

return PyLong_FromLong(a);
}

static PyMethodDef module_methods[] = {
{ "ext_fibo", (PyCFunction)ext_fibo, METH_VARARGS, "Extension Fibo"},
{ NULL, NULL, 0, NULL }
};

static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT, "ext_fibo",
NULL, -1, module_methods
};

PyMODINIT_FUNC PyInit_ext_fibo(){
return PyModule_Create(&moduledef);
}
11 changes: 11 additions & 0 deletions python_ext/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from distutils.core import Extension
from distutils.core import setup

py_ext = Extension('ext_fibo', sources=['ext_fibo.c'])

setup(name='Extension PKG',
version='1.0',
description='This is a demo package',
ext_modules=[py_ext])

# Run command: python setup.py install