【发布时间】:2015-11-09 11:18:26
【问题描述】:
我有以下Cython 代码:
# 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())
当我尝试从python3 控制台运行它时,我收到错误:
NameError: name 'run_io' is not defined
如果我将run_io 函数cdef 的定义更改为def,它会起作用:
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}
但是,这不是很丰富,因为我只看到整个函数的总运行时间(我希望看到生成文件名、读取、写入等的部分运行时间)。
因此,我有两个问题:
是否可以分析
Cython函数(使用cdef定义)?如果是,怎么做?如何使分析提供更多信息(即测量每个调用函数所花费的时间)?
【问题讨论】: