一、减少间接访问
<span style="white-space:pre"> </span>D_Ascii = { } #this will save time about 0.1s
D_Freq = { } #avoid create&destroy a pointer in for loop
for index_Word in range(len(lines_Word)-2):
index_AsciiHash = ord(lines_Word[index_Word][0]) #this one costs 1.4 s
str_Key = lines_Word[index_Word][0:-1] + str_const_GLUE + lines_Word[index_Word+1][0:-1] #costs 1.4s
#str_Key = f_glue_word(lines_Word[index_Word][:-1],lines_Word[index_Word+1][:-1]) #costs 2.5s
str_NextWord = lines_Word[index_Word+2][:-1] #costs 0.5s
D_Ascii = self.list_AsciiHash[index_AsciiHash] #datatype -- dict_AciiHash_Dict
D_Freq = self.list_KeyFreq_Dict_asciihash[index_AsciiHash] #costs 0.5s
在上面的例子中,D_Ascii和D_Freq的定义就是为了加入一个二级hash访问的临时变量
看似不经意的举动,会提高多少速度呢?
大约0.2秒。
一个典型的时间换空间的例子。这还是简单的间接访问,如果是复杂的访问则会节省更多的时间了~!
即简化了代码的长度,又提高了效率,何乐而不为呢?
二、if判断条件也会影响时间?
if str_Key not in D_Ascii: #put "not in" in front of "in",save 0.4s, because in will cause extra judge
D_Ascii[str_Key] = { str_NextWord : 1 }#costs 1.4s
D_Freq[str_Key] = 1#555
else:
if str_NextWord in D_Ascii[str_Key]:#666
D_Ascii[str_Key][str_NextWord]+=1#666
else:#666
D_Ascii[str_Key][str_NextWord]=1#666
D_Freq[str_Key] += 1#555
上面这段代码,用的是if not in 而不是 if in, 一般都觉得这没什么嘛,不就是换个顺序?
但是实际在测试的时候,我却发现,if not比if要节省了0.4秒的时间!
为何会这样?
。。。。。。。。。。。。。。。
我也没找到合理的解释………………
三、函数调用也会消耗资源!
在性能分析的时候,我发现某些函数竟然调用了200W次之多!
其中有一个函数的作用是在A和B中间加入一段字符串“_+_”。为了简化代码我专门弄了一个函数,没想到这个函数竟然消耗的时间竟然达到3秒!
后来我把这个函数去掉,直接进行连接,发现只需要消耗1.3秒!
总结1:函数调用,能省则省。
同样的一个例子,str的方法strip()。
我需要处理的是一个末尾带'\n'的字符串,那么对于这个操作,我只需要使用word[0:-1]即可,并不需要使用strip()
因为这个函数有一些其他功能,包括去头去尾!
那么节省了多少时间呢?一半,1.5s!
(完)我对这篇文章不太满意,因为我发现用数据库不需要经过这么痛苦的数据处理过程。唉…
这种感觉就跟…………