python中if的效率_python优化代码(文本查找)效率?

发现一个很有意思的事情, 大家回答很积极, 但是实际结果呢, 我刚好无聊小测试了一下, 过程如下:

介于题主提供的示例文本才两行, 所以我把1.txt和genemark.gff3分别加倍到4000行

(qiime) [ngs@cluster ~]$ wc -l 1.txt

4000 1.txt

(qiime) [ngs@cluster ~]$ wc -l genemark.gff3

4000 genemark.gff3

按照回复楼层数排序, 如题主的代码是hi.py,然后一楼答主的代码是hi1.py,依次类推

先看题主的

(qiime) [ngs@cluster ~]$ time python hi.py > hi.txt

real 0m0.049s

user 0m0.042s

sys 0m0.007s

(qiime) [ngs@cluster ~]$ wc -l hi.txt

6000 hi.txt

感觉是有重复

一楼答主的

time python hi1.py > hi1.txt

real 0m21.727s

user 0m21.171s

sys 0m0.547s

(qiime) [ngs@cluster ~]$ wc -l hi1.txt

8000000 hi1.txt

重复到姥姥家了

二楼答主的

(qiime) [ngs@cluster ~]$ time python hi2.py > hi2.txt

real 0m16.326s

user 0m14.550s

sys 0m1.044s

(qiime) [ngs@cluster ~]$ wc -l hi2.txt

12000000 hi2.txt

三楼答主的

(qiime) [ngs@cluster ~]$ time python hi3.py > hi3.txt

real 0m27.079s

user 0m26.281s

sys 0m0.786s

(qiime) [ngs@cluster ~]$ wc -l hi3.txt

12000000 hi3.txt

三楼答主的结果跟二楼一样, 但是慢了10秒多

四楼答主的(冤枉四楼同学了,这是py3代码)

(py3) [ngs@cluster ~]$ time python hi4.py > hi4.txt

real 0m0.074s

user 0m0.064s

sys 0m0.010s

(py3) [ngs@cluster ~]$ wc -l hi4.txt

4000 hi4.txt

果然是有交流才有进步, 目前这个结果才是正确的

总结

实际好像是题主的代码结果会有重复, 四楼答主的结果才是正确的

我的方案--把四楼的代码小改变成并行的

我写的有问题, @用筹兮用严 更新了正确的并行代码, 我的代码就不改了, 方便后面看到的同学参考

直接放码(python3)

from collections import defaultdict

import multiprocessing

def find_sth(x):

with open('1.txt', 'r') as f1:

infile1 = defaultdict(set)

for uno1, chr1, start1, end1, *others in map(str.split, f1):

infile1[chr1].add((uno1, int(start1), int(end1)))

chr, start, end, info = x[0], int(x[3]), int(x[4]), x[-1]

for uno1, start1, end1 in infile1[chr]:

if start1 < start < end1 or start1 < end < end or (start1 > start and end > end1):

print(uno1, info)

def main():

with open('genemark.gff3', 'r') as fh:

lst = [x for x in map(str.split, fh) if x[2] == 'gene']

pool = multiprocessing.Pool(multiprocessing.cpu_count())

pool.map(find_sth, lst)

pool.close()

pool.join()

if __name__ == "__main__":

main()

然后看看运行效率

(py3) [ngs@cluster ~]$ time python hi_new.py > hi_new.txt

real 0m3.033s

user 0m31.952s

sys 0m0.219s

(py3) [ngs@cluster ~]$ wc -l hi_new.txt

4000 hi_new.txt

时间上貌似慢了很多(4000行数据才几百KB), 题主可以试着用你的真实数据测试下, 处理数据越大, 并行处理的效率优势越明显

PS: 我估计题主实际处理的数据大小得有MB甚至是GB级别, 这种级别并行处理才是王道

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值