Skip to content

Instantly share code, notes, and snippets.

@yuokada
Created December 4, 2011 16:49
Show Gist options
  • Save yuokada/1430650 to your computer and use it in GitHub Desktop.
Save yuokada/1430650 to your computer and use it in GitHub Desktop.
python-Hello.c
/* 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);
}
.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
#!/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)
@yuokada
Copy link
Author

yuokada commented Jul 15, 2012

% which python2.7
/usr/bin/python2.7

% python2.7  timer_mon.py 
pure python time : 0.590466976166
c module time    : 0.521992921829

% python2.7  timer_mon.py
pure python time : 0.615018129349
c module time    : 0.534858942032

% python2.7  timer_mon.py
pure python time : 0.626820087433
c module time    : 0.525256872177

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