Skip to main content
 首页 » 编程设计

python之为什么 python zipfile 模块比 C 快

2024年10月24日14Renyi-Fan

我正在编写一个需要能够非常快速地处理大量 zip 文件的模块。因此,我打算使用用 C 而不是 Python 实现的东西(我将从中调用提取器)。为了尝试测试哪种方法最快,我编写了一个测试脚本来比较 linux 的“unzip”命令与 czipfile python 模块(c zip 提取器的包装器)。作为对照,我使用了 native python zipfile 模块。

该脚本创建一个 zip 文件,在 100 ~1MB 文件中大约有 100MB。它着眼于 3 种情况。 A) 这些文件都是随机字节串。 B)文件只是随机的十六进制字符 C)文件是带有换行符的统一随机句子。

在所有情况下,zipfile(用 python 实现)的性能与用 c 实现的两个提取器相当或明显更好。

知道为什么会发生这种情况吗?脚本已附上。需要 shell 中可用的 czipfile 和“unzip”命令。

from datetime import datetime 
import zipfile 
import czipfile 
import os, binascii, random 
 
class ZipTestError(Exception): 
    pass 
 
 
 
class ZipTest: 
 
    procs = ['zipfile', 'czipfile', 'os'] 
    type_map = {'r':'Random', 'h':'Random Hex', 's':'Sentences'} 
 
    # three types. t=='r' is random noise files directly out of urandom. t=='h' is urandom noise converted to ascii characters. t=='s' are randomly constructed sentences with line breaks. 
    def __init__(self): 
        print """Testing Random Byte Files: 
""" 
        self.test('r') 
        self.test('h') 
        self.test('s') 
 
 
 
 
    @staticmethod 
    def rand_name(): 
        return binascii.b2a_hex(os.urandom(10)) 
 
    def make_file(self, t):  
        f_name = self.rand_name() 
        f = open(f_name, 'w') 
        if t == 'r': 
            f.write(os.urandom(1048576)) 
        elif t == 'h': 
            f.write(binascii.b2a_hex(os.urandom(1048576))) 
        elif t == 's': 
            for i in range(76260): 
                ops = ['dog', 'cat', 'rat'] 
                ops2 = ['meat', 'wood', 'fish'] 
                n1 = int(random.random()*10) % 3 
                n2 = int(random.random()*10) % 3 
                sentence = """The {0} eats {1} 
    """.format(ops[n1], ops2[n2]) 
                f.write(sentence) 
        else: 
            raise ZipTestError('Invalid Type') 
        f.close() 
        return f_name 
 
    #create a ~100MB zip file to test extraction on. 
    def create_zip_test(self, t): 
        self.file_names = [] 
        self.output_names = [] 
        for i in range(100): 
            self.file_names.append(self.make_file(t)) 
        self.zip_name = self.rand_name() 
        output = zipfile.ZipFile(self.zip_name, 'w', zipfile.ZIP_DEFLATED) 
        for f in self.file_names: 
            output.write(f) 
        output.close() 
 
 
    def clean_up(self, rem_zip = False): 
        for f in self.file_names: 
            os.remove(f) 
        self.file_names = [] 
        for f in self.output_names: 
            os.remove(f) 
        self.output_names = [] 
        if rem_zip: 
            if getattr(self, 'zip_name', False): 
                os.remove(self.zip_name) 
            self.zip_name = False 
 
    def display_res(self, res, t): 
        print """ 
{0} results: 
""".format(self.type_map[t]) 
        for p in self.procs: 
            print""" 
{0} = {1} milliseconds""".format(p, str(res[p])) 
 
 
    def test(self, t): 
        self.create_zip_test(t) 
        res = self.unzip() 
        self.display_res(res, t) 
        self.clean_up(rem_zip = True) 
 
 
    def unzip(self): 
        res = dict() 
        for p in self.procs: 
            self.clean_up() 
            res[p] = getattr(self, "unzip_with_{0}".format(p))() 
        return res 
 
    def unzip_with_zipfile(self): 
        return self.unzip_with_python(zipfile) 
 
    def unzip_with_czipfile(self): 
        return self.unzip_with_python(czipfile) 
 
    def unzip_with_python(self, mod): 
        f = open(self.zip_name) 
        zf = mod.ZipFile(f) 
        start = datetime.now() 
        op = './' 
        for name in zf.namelist(): 
            zf.extract(name,op) 
            self.output_names.append(name) 
        end = datetime.now() 
        total = end-start 
        ms = total.microseconds 
        ms += (total.seconds) * 1000000 
        return ms /1000 
 
    def unzip_with_os(self): 
        f = open(self.zip_name) 
        start = datetime.now() 
        zf = zipfile.ZipFile(f) 
        for name in zf.namelist(): 
            self.output_names.append(name)    
        os.system("unzip -qq {0}".format(f.name)) 
        end = datetime.now() 
        total = end-start 
        ms = total.microseconds 
        ms += (total.seconds) * 1000000 
        return ms /1000 
 
 
 
 
 
 
if __name__ == '__main__': 
    ZipTest() 

请您参考如下方法:

正如上面所指出的,解密是在 python 中完成的,而不是解压缩。所以 zipfile 只是像其他两个一样使用 c 实现。