I have the following Cython
code:
# cython: profile=True
import cProfile
from cython import parallel
from libc.stdio cimport FILE, fopen, fclose, fwrite, getline, printf
from libc.string cimport strlen
from libcpp.string cimport string
cdef extern from "stdio.h" nogil:
int mkstemp(char*);
cdef run_io(string obj):
cdef int i, dump
cdef size_t len_ = 0
cdef char* fname = "/tmp/tmpc_XXXXXX"
cdef char* nullchar = NULL
cdef char* line = NULL
cdef string content = b""
cdef FILE* cfile
for i in range(10000):
dump = mkstemp(fname)
cfile = fopen(fname, "wb")
fwrite(obj.data(), 1, obj.size(), cfile)
fclose(cfile)
cfile = fopen(fname, "rb")
while True:
if getline(&line, &len_, cfile) == -1:
break
else:
content.append(line)
fclose(cfile)
def run_test():
cdef string obj = b"abc\ndef"
cProfile.runctx("run_io(obj)", globals(), locals())
When I try to run it from a python3
console, I get the error:
NameError: name 'run_io' is not defined
If I change in the definition of the run_io
function cdef
to def
, it works:
7 function calls in 2.400 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.400 2.400 <string>:1(<module>)
2 0.000 0.000 0.000 0.000 stringsource:13(__pyx_convert_string_from_py_std__in_string)
1 2.400 2.400 2.400 2.400 testc2.pyx:10(run_io)
1 0.000 0.000 2.400 2.400 {built-in method exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 2.400 2.400 {test.run_io}
However, this is not very informative, as I see only the total runtime for the whole function (and I would like to see the partial runtimes for generating filename, reading, writing, etc.).
Therefore, I have two questions:
Is it possible to profile
Cython
functions (defined withcdef
)? If yes, how?How to make profiling more informative (i.e. measure time spent in each called function)?