我有一个函数,它读取二进制文件并将每个字节转换成相应的字符序列。例如,0x05变为'AACC',0x2A变为'AGGG'等…读取文件并转换字节的函数目前是线性函数,由于要转换的文件介于25kb和2Mb之间,这可能需要相当长的时间。在
因此,我尝试使用多处理来划分任务,希望能提高速度。但是,我就是不能让它工作。下面是一个线性函数,它工作得很慢
def fileToRNAString(_file):
if (_file and os.path.isfile(_file)):
rnaSequences = []
blockCount = 0
blockSize = 2048
printAndLog("!", "Converting %s into RNA string (%d bytes/block)" % (_file, blockSize))
with open(_file, "rb") as hFile:
buf = hFile.read(blockSize)
while buf:
decSequenceToRNA(blockCount, buf, rnaSequences)
blockCount = blockCount + 1
buf = hFile.read(blockSize)
else:
printAndLog("-", "Could not find the specified file. Please verify that the file exists:" + _file)
return rnaSequences
注意:函数'decSequenceToRNA'接受缓冲区读取并将每个字节转换为所需的字符串。在执行时,函数返回一个包含块号和字符串的元组,例如(1,'ACCGTAGATTA…'),最后,我有一个这些元组的数组可用。在
我试图将函数转换为使用Python的多处理
^{pr2}$但是,似乎没有进程启动,因为当这个函数运行时,返回一个空数组。在“decSequenceToRNA”中打印到控制台的任何消息都不会显示
>>>fileToRNAString(testfile)
[!] Converting /root/src/amino56/M1H2.bin into RNA string (2048 bytes/block).
与这里的question不同,我运行的是LinuxShiva 3.14-kali1-amd64#1smpdebian 3.14.5-1kali1(2014-06-07)x86_64 GNU/Linux,并使用pyrclast在Python版本2.7.3上测试函数。我正在使用以下软件包:
import os
import re
import sys
import urllib2
import requests
import logging
import hashlib
import argparse
import tempfile
import shutil
import feedparser
from multiprocessing import Process
我想知道为什么我的代码不起作用,或者我在其他地方遗漏了一些东西来让这个过程正常工作。同时也欢迎改进代码的建议。以下是“decSequenceToRNA”以供参考:
def decSequenceToRNA(_idxSeq, _byteSequence, _rnaSequences):
rnaSequence = ''
printAndLog("!", "Processing block %d (%d bytes)" % (_idxSeq, len(_byteSequence)))
for b in _byteSequence:
rnaSequence = rnaSequence + base10ToRNA(ord(b))
printAndLog("+", "Block %d completed. RNA of %d nucleotides generated." % (_idxSeq, len(rnaSequence)))
_rnaSequences.append((_idxSeq, rnaSequence))
试着写这个(参数列表末尾的逗号)
decSequenceToRNA
在它自己的进程中运行,这意味着它在主进程中获得每个数据结构的独立副本。这意味着当您在decSequenceToRNA
中追加_rnaSequences
时,它对父进程中的rnaSequences
没有任何影响。这就解释了为什么返回一个空列表。在你有两个选择来解决这个问题。首先,创建一个^{} ,它可以使用
multiprocessing.Manager
在进程之间共享。例如:输出:
^{pr2}$将此应用于代码只需替换
与
或者,您可以(也可能应该)使用^{} ,而不是为每个块创建单独的} 块,那么您将因为为每个块生成进程而损害性能。使用
Process
。我不确定hFile
有多大,或者您正在读取的块有多大,但是如果有超过^{Pool
,您可以保持进程计数不变,并轻松创建rnaSequence
列表:请注意,我们不再将
rnaSequences
列表传递给孩子。相反,我们只需将返回的结果返回给父对象(我们不能使用Process
),并在那里构建列表。在相关问题 更多 >
编程相关推荐