gpt4 book ai didi

Python Line_profiler 和 Cython 函数

转载 作者:太空狗 更新时间:2023-10-29 20:37:11 25 4
gpt4 key购买 nike

所以我尝试使用 line_profiler 在我自己的 python 脚本中分析一个函数,因为我想要逐行计时。唯一的问题是该函数是 Cython 函数,并且 line_profiler 无法正常工作。在第一次运行时,它只是因错误而崩溃。然后我添加了

!python
cython: profile=True
cython: linetrace=True
cython: binding=True

在我的脚本的顶部,现在它运行正常,除了时间和统计数据是空白的!

有没有办法将 line_profiler 与 Cythonized 函数一起使用?

我可以分析非 Cythonized 函数,但它比 Cythonized 慢得多,以至于我无法使用来自分析的信息 - 纯 python 函数的缓慢使得我无法改进 Cython一个。

这是我要分析的函数的代码:

class motif_hit(object):
__slots__ = ['position', 'strand']

def __init__(self, int position=0, int strand=0):
self.position = position
self.strand = strand

#the decorator for line_profiler
@profile
def find_motifs_cython(list bed_list, list matrices=None, int limit=0, int mut=0):
cdef int q = 3
cdef list bg = [0.25, 0.25, 0.25, 0.25]
cdef int matrices_length = len(matrices)
cdef int results_length = 0
cdef int results_length_shuffled = 0
cdef np.ndarray upper_adjust_list = np.zeros(matrices_length, np.int)
cdef np.ndarray lower_adjust_list = np.zeros(matrices_length, np.int)
#this one need to be a list for MOODS
cdef list threshold_list = [None for _ in xrange(matrices_length)]
cdef list matrix_list = [None for _ in xrange(matrices_length)]
cdef np.ndarray results_list = np.zeros(matrices_length, np.object)
cdef int count_seq = len(bed_list)
cdef int mat
cdef int i, j, k
cdef int position, strand
cdef list result, results, results_shuffled
cdef dict result_temp
cdef int length
if count_seq > 0:
for mat in xrange(matrices_length):
matrix_list[mat] = matrices[mat]['matrix'].tolist()
#change that for a class
results_list[mat] = {'kmer': matrices[mat]['kmer'],
'motif_count': 0,
'pos_seq_count': 0,
'motif_count_shuffled': 0,
'pos_seq_count_shuffled': 0,
'ratio': 0,
'sequence_positions': np.empty(count_seq, np.object)}
length = len(matrices[mat]['kmer'])
#wrong with imbalanced matrices
upper_adjust_list[mat] = int(ceil(length / 2.0))
lower_adjust_list[mat] = int(floor(length / 2.0))
#upper_adjust_list[mat] = 0
#lower_adjust_list[mat] = 0
#-0.1 to adjust for a division floating point bug (4.99999 !< 5, but is < 4.9!)
threshold_list[mat] = MOODS.max_score(matrix_list[mat]) - float(mut) - 0.1

#for each sequence
for i in xrange(count_seq):
item = bed_list[i]
#TODO: remove the Ns, but it might unbalance
results = MOODS.search(str(item.sequence[limit:item.total_length - limit]), matrix_list, threshold_list, q=q, bg=bg, absolute_threshold=True, both_strands=True)
results_shuffled = MOODS.search(str(item.sequence_shuffled[limit:item.total_length - limit]), matrix_list, threshold_list, q=q, bg=bg, absolute_threshold=True, both_strands=True)
results = results[0:len(matrix_list)]
results_shuffled = results_shuffled[0:len(matrix_list)]
results_length = len(results)
#for each matrix
for j in xrange(results_length):
result = results[j]
result_shuffled = results_shuffled[j]
upper_adjust = upper_adjust_list[j]
lower_adjust = lower_adjust_list[j]
result_length = len(result)
result_length_shuffled = len(result_shuffled)
if result_length > 0:
results_list[j]['pos_seq_count'] += 1
results_list[j]['sequence_positions'][i] = np.empty(result_length, np.object)
#for each motif
for k in xrange(result_length):
position = result[k][0]
strand = result[k][1]
if position >= 0:
strand = 0
adjust = upper_adjust
else:
position = -position
strand = 1
adjust = lower_adjust
results_list[j]['motif_count'] += 1
results_list[j]['sequence_positions'][i][k] = motif_hit(position + adjust + limit, strand)

if result_length_shuffled > 0:
results_list[j]['pos_seq_count_shuffled'] += 1
#for each motif
for k in xrange(result_length_shuffled):
results_list[j]['motif_count_shuffled'] += 1

#j = j + 1
#i = i + 1

for i in xrange(results_length):
result_temp = results_list[i]
result_temp['ratio'] = float(result_temp['pos_seq_count']) / float(count_seq)
return results_list

我很确定三重嵌套循环是主要的缓慢部分 - 它的工作只是重新排列来自 MOODS 的结果,C 模块执行主要工作。

最佳答案

Till Hoffmann 在此处提供了有关在 Cython 中使用 line_profiler 的有用信息:How to profile cython functions line-by-line .

我引用他的解决方案:

Robert Bradshaw 帮助我获得了用于 cdef 函数的 Robert Kern 的 line_profiler 工具,我想我应该在 stackoverflow 上分享结果。

简而言之,设置一个常规的 .pyx 文件并构建脚本和 pass to cythonize linetrace compiler directive启用分析和线路跟踪:

from Cython.Build import cythonize

cythonize('hello.pyx', compiler_directives={'linetrace': True})

您可能还想设置 ( undocumented ) directive bindingTrue

另外,您应该通过修改您的扩展设置来定义 C 宏 CYTHON_TRACE=1

extensions = [
Extension('test', ['test.pyx'], define_macros=[('CYTHON_TRACE', '1')])
]

iPython 笔记本中使用 %%cython 魔法的工作示例如下: http://nbviewer.ipython.org/gist/tillahoffmann/296501acea231cbdf5e7

关于Python Line_profiler 和 Cython 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24144931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com