【问题标题】:python dict timing mysterypython dict计时之谜
【发布时间】:2014-01-22 16:00:13
【问题描述】:

我正在做序列比对,并且遇到了一个与我的 dict 数据结构的起源有关的相当神秘的时间问题。 基本上,我有功能alignment(s1, s2, scores) 它包含两个字符串 s1 和 s2,以及每个可能的 20 个氨基酸对和一个间隙“-”的评分矩阵(作为 python 字典)。所以scores 有 440 个键(char1,char2),具有整数值。

这就是谜团:如果我从文本文件中读取scores(称为 score1)并运行 alignment(s1, s2, scores1) 对于一些 1000-ish 长的氨基酸字符串 s1、s2,我得到以下时间(使用 cProfile 并且不显示函数输出):

2537776 function calls in 11.796 seconds

现在,如果我在我的文件中创建完全相同的字典(称为 score2)并运行 alignment(s1, s2, scores2) 我得到了相同的输出结果,但时间缩短了 3 倍:

2537776 function calls in 4.263 seconds

两种情况下的输出是相同的,只是时间不同。 运行print scores1 == scores2 会产生True,因此它们包含相同的信息。 我验证了使用访问字典的任意函数(而不是对齐) 在这两种情况下,多次产生相同的因子 3 时序差异。

一定有一些元数据与字典的来源相关,这会减慢我的功能(当来自文件时),即使在这两种情况下我实际上都在文件中读取。 我尝试通过scores1 = dict(scores1) 等为每个创建一个新的 dict 对象,但同样的时间差异仍然存在。相当混乱,但我敢肯定,如果我能弄明白,这会是一个很好的教训。

scores1 = create_score_dict_from_file('lcs_scores.txt')
scores2 = create_score_dict(find_alp(s1, s2), match=1, mismatch=0, indel=0)
print scores1 == scores2   # True
alignment(s1, s2, scores1) # gives right answer in about 12s
alignment(s1, s2, scores2) # gives right answer in about 4s

编辑:在下面添加代码和结果:

这是代码的简化版本:

import numpy as np
from time import time

def create_scores_from_file(score_file, sigma=0):
    """
    Creates a dict of the scores for each pair in an alphabet,
    as well as each indel (an amino acid, paired with '-'), which is scored -sigma.

    """
    f = open(score_file, 'r')
    alp = f.readline().strip().split()
    scores = []
    for line in f:
        scores.append(map(int, line.strip().split()[1:]))
    f.close()
    scores = np.array(scores)
    score_dict = {}
    for c1 in range(len(alp)):
        score_dict[(alp[c1], '-')] = -sigma
        score_dict[('-', alp[c1])] = -sigma
        for c2 in range(len(alp)):
            score_dict[(alp[c1], alp[c2])] = scores[c1, c2]
    return score_dict

def score_matrix(alp=('A', 'C', 'G', 'T'), match=1, mismatch=0, indel=0):
    score_dict = {}
    for c1 in range(len(alp)):
        score_dict[(alp[c1], '-')] = indel
        score_dict[('-', alp[c1])] = indel
        for c2 in range(len(alp)):
            score_dict[(alp[c1], alp[c2])] = match if c1 == c2 else mismatch
    return score_dict

def use_dict_in_function(n, d):
    start = time()
    count = 0
    for i in xrange(n):
        for k in d.keys():
            count += d[k]
    print "Time: ", time() - start
    return count

def timing_test():
    alp = tuple('A  C  D  E  F  G  H  I  K  L  M  N  P  Q  R  S  T  V  W  Y'.split())
    scores1 = create_scores_from_file('lcs_scores.txt')
    scores2 = score_matrix(alp, match=1, mismatch=0, indel=0)
    print type(scores1), id(scores1)
    print type(scores2), id(scores2)
    print repr(scores1)
    print repr(scores2)
    print type(list(scores1)[0][0])
    print type(list(scores2)[0][0])
    print scores1 == scores2
    print repr(scores1) == repr(scores2)
    n = 10000
    use_dict_in_function(n, scores1)
    use_dict_in_function(n, scores2)

if __name__ == "__main__":
    timing_test()

结果是:

<type 'dict'> 140309927965024
<type 'dict'> 140309928036128
{('S', 'W'): 0, ('G', 'G'): 1, ('E', 'M'): 0, ('P', '-'): 0,... (440 key: values)
{('S', 'W'): 0, ('G', 'G'): 1, ('E', 'M'): 0, ('P', '-'): 0,... (440 key: values)
<type 'str'>
<type 'str'>
True
True
Time:  1.51075315475
Time:  0.352770090103

这是 lcs_scores.txt 文件的内容:

   A  C  D  E  F  G  H  I  K  L  M  N  P  Q  R  S  T  V  W  Y
A  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
C  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
D  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
E  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
F  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
G  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
H  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  
I  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  
K  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  
L  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  
M  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  
N  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  
P  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  
Q  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  
R  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  
S  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  
T  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  
V  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  
W  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  
Y  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  

【问题讨论】:

    标签: python dictionary numpy alignment timing


    【解决方案1】:

    哪个版本的 Python?并打印每个 dict 的 repr() 以确保它们确实相同(而不是 只是 它们比较相等)。猜不透。例如,也许您使用的是 Python 2,在一种情况下,您的 char1char2 是纯字符串,但在另一种情况下,它们是 Unicode 字符串。然后比较会说它们是相同的,但repr() 会显示差异:

    >>> d1 = {"a": 1}
    >>> d2 = {u"a": 1}
    >>> d1 == d2
    True
    >>> print repr(d1), repr(d2)
    {'a': 1} {u'a': 1}
    

    无论如何,在 CPython 中,绝对没有任何内部“元数据”记录任何对象的来源。

    编辑 - 尝试一下

    解决问题的出色工作!这正在成为一种乐趣 :-) 我希望你尝试一下。首先注释掉这一行:

        scores = np.array(scores)
    

    然后改变这一行:

                score_dict[(alp[c1], alp[c2])] = scores[c1, c2]
    

    到:

                score_dict[(alp[c1], alp[c2])] = scores[c1][c2]
                                                        ^^^^^^
    

    当我这样做时,这两种方法返回的时间基本相同。我不是 numpy 专家,但我的猜测是,您的“来自文件”代码使用机器原生 numpy 整数类型作为 dict 值,并且每当使用值。

    也许不是——但这是我现在的猜测,我会坚持下去;-)

    【讨论】:

    • Python 2.7.5 repr() 给出相同的结果:{('S', 'W'): 0, ('G', 'G'): 1, ('E', 'M'): 0, ('P', '-'): 0,...
    • 那么你确实有一个谜——但你已经知道了 ;-) 我和地球上任何人一样了解 CPython 的 dict 实现,而且我没有其他理论。除非其他人提出了一个绝妙的主意,否则恐怕您必须发布足够多的代码,以便其他人可以重现您的问题。
    • 远射:可能,如果键以不同的顺序添加到字典中,repr 可能相同,但冲突的内部顺序哈希表不同。如果某些键比其他键被更频繁地引用,并且在一种情况下被大量引用的键遭受长冲突链,这可能会产生影响。但是我在复合不可能性,并且没有办法从 Python 代码中获取字典的内部结构。我想您可以尝试对每个单独的键进行定时访问:scores1 中的一个或两个键可能需要更长的时间-或者它们全部需要更长的时间-或者...
    • 是的。谢谢您的帮助。经验教训:对数据类型要非常小心!并且不要将 numpy 数据类型与内置数据类型混合使用。
    • 顺便说一句,很遗憾numpy 在使用其中一种类型时没有实现repr显示。 Python 非常小心地确保,例如,repr() 为整数、浮点数、ahd 复数返回不同的字符串,即使它们比较相等。
    猜你喜欢
    • 2015-04-16
    • 2011-08-20
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多