Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python高效地分配预定义大小的文件并用非零值填充它?_Python_Linux_Windows_File_Bigdata - Fatal编程技术网

如何使用Python高效地分配预定义大小的文件并用非零值填充它?

如何使用Python高效地分配预定义大小的文件并用非零值填充它?,python,linux,windows,file,bigdata,Python,Linux,Windows,File,Bigdata,我正在写一个程序,用动态规划来解决一个难题。DP解决方案需要存储一个大表。整个表大约占用300 Gb。物理上它存储在40~7Gb的文件中。我正在用字节\xFF标记未使用的表条目。我想尽快为这张桌子分配空间。该程序必须在Windows和Linux下运行 简而言之,我希望以跨平台的方式高效地创建填充特定字节的大型文件 以下是我当前使用的代码: def reset_storage(self, path): fill = b'\xFF' with open(path, 'wb') as

我正在写一个程序,用动态规划来解决一个难题。DP解决方案需要存储一个大表。整个表大约占用300 Gb。物理上它存储在40~7Gb的文件中。我正在用字节
\xFF
标记未使用的表条目。我想尽快为这张桌子分配空间。该程序必须在Windows和Linux下运行

简而言之,我希望以跨平台的方式高效地创建填充特定字节的大型文件

以下是我当前使用的代码:

def reset_storage(self, path):
    fill = b'\xFF'

    with open(path, 'wb') as f:
        for _ in range(3715948544 * 2):
            f.write(fill)
创建一个7 Gb文件大约需要40分钟。我如何加速它

我看了其他问题,但没有一个是相关的:

  • -没有回答
  • -文件中填充了
    \0
    ,或者解决方案仅适用于Windows
  • -所有解决方案都是特定于Linux的

您的问题是经常调用python方法(针对每个字节!)。我所提供的肯定不是完美的,但会更快很多倍。请尝试以下操作:

fill = b"\xFF" * 1024 * 1024  # instantly 1 MiB of ones
...
file_size = 300 * 1024  # in MiB now!
with open(path, 'wb') as f:
    for _ in range(file_size):
        f.write(fill)

写入块,而不是字节,并避免无理由地迭代巨大的
范围

import itertools

def reset_storage(self, path):
    total = 3715948544 * 2
    block_size = 4096  # Tune this if needed, just make sure it's a factor of the total
    fill = b'\xFF' * block_size

    with open(path, 'wb') as f:
        f.writelines(itertools.repeat(fill, total // block_size))
        # If you want to handle initialization of arbitrary totals without
        # needing to be careful that block_size evenly divides total, add
        # a single:
        # f.write(fill[:total % block_size])
        # here to write out the incomplete block.
理想的块大小因系统而异。一个合理的选择是使用
io.DEFAULT\u BUFFER\u SIZE
自动匹配写入到刷新,同时保持较低的内存使用率