在Python中交换大文件字节的最快方法

2024-09-28 17:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个项目,我需要快速交换4字节的字。在使用其他计算算法之前,我需要切换大文件(2mb)的每个字(4字节)

def word_swaper(data):
    buf_swaped_data = b""

    number_of_words = int(len(data) / 4)

    for word in range(number_of_words):
        newword = data[word*4:(word+1)*4]
        newword = newword[::-1]
        buf_swaped_data += newword

有没有更快或更简单的方法?我将用它来处理大小约为2mb的文件,因此计算时间约为1-2分钟,这太长了


Tags: 文件of项目算法numberdata字节def
1条回答
网友
1楼 · 发布于 2024-09-28 17:31:04

使用两个io.BytesIO()的基准测试在我的机器上的速度是3倍以上但是there's a built-in method for this这比我的机器快550倍

import timeit
import os
import io
import array


def original(data):
    buf_swaped_data = b""

    number_of_words = int(len(data) / 4)

    for word in range(number_of_words):
        newword = data[word * 4 : (word + 1) * 4]
        newword = newword[::-1]
        buf_swaped_data += newword
    return buf_swaped_data


def io_pair(data):
    in_io = io.BytesIO(data)
    out_io = io.BytesIO()
    while True:
        word = in_io.read(4)
        if not word:
            break
        out_io.write(word[::-1])
    return out_io.getvalue()


def array_swap(data):
    arr = array.array("L", data)
    arr.byteswap()
    return bytes(arr)


def t(f):
    data = b"1234" * 8000
    assert f(data) == original(data)
    count, time_taken = timeit.Timer(lambda: f(data)).autorange()
    print(f.__name__, count / time_taken)


t(original)
t(io_pair)
t(array_swap)
original      186.465
io_pair       568.180
array_swap 102897.423

相关问题 更多 >