Created
December 4, 2011 16:49
-
-
Save yuokada/1430650 to your computer and use it in GitHub Desktop.
python-Hello.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* hello.c */ | |
#include "Python.h" | |
static PyObject * hello(PyObject *self) | |
{ | |
printf("Hello World!!\n"); | |
Py_RETURN_NONE; | |
} | |
static char hello_doc[] = "hello module\n"; | |
static PyObject * | |
hello_you (PyObject * self, PyObject * args){ | |
/* | |
const char *name; | |
static PyObject *format = NULL; | |
PyObject *result; | |
PyArg_ParseTuple(args, "s", &name); | |
if(!PyArg_ParseTuple(args, "s", &name)){ | |
PyErr_SetString(MissingKeyException, "Missing parameter: name"); | |
} | |
*/ | |
const char *name; | |
if(!PyArg_ParseTuple(args, "s", &name)){ | |
//PyErr_SetString(MissingKeyException, "Missing parameter: name"); | |
return NULL; | |
} | |
return Py_BuildValue("s", name); | |
/* | |
//sprintf(greeting, "Hello world! %s.\n", name); | |
format = PyString_FromString("Helo %s"); | |
result = PyString_Format(format, name); | |
return result; | |
*/ | |
} | |
static PyMethodDef methods[] = { | |
{"hello", (PyCFunction)hello, METH_NOARGS, "print hello world.\n"}, | |
{"hello_you", (PyCFunction)hello_you, METH_VARARGS, "print hello world (you).\n"}, | |
{NULL, NULL, 0, NULL} | |
}; | |
void inithello(void) | |
{ | |
Py_InitModule3("hello", methods, hello_doc); | |
Py_InitModule3("hello_you", methods, hello_doc); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.PHONY all: | |
gcc -m64 -fPIC -Wall -I/opt/local/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c hello.c | |
gcc -m64 -shared -o hello.so -lpython hello.o |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
import hello | |
import timeit | |
def pure_hello(name): | |
return "hello world %s\n" % name | |
def bench1(): | |
name = "yuokada" | |
return pure_hello(name) | |
def bench2(): | |
name = "yuokada" | |
return hello.hello_you(name) | |
if __name__ == '__main__': | |
t = timeit.Timer("bench1()", "from __main__ import bench1") | |
print "pure python time :", t.timeit(number=1000000) | |
t = timeit.Timer("bench2()", "from __main__ import bench2") | |
print "c module time :", t.timeit(number=1000000) | |
Author
yuokada
commented
Jul 15, 2012
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment