【发布时间】:2018-07-24 00:46:42
【问题描述】:
我需要生成 10GB 的随机数据。
我编写了以下 python 脚本,通过将包含随机长度的可打印 ASCII 字符的字符串写入文件的每一行来生成所需的字节数
它需要 3 个命令行参数。 1) 尺寸 2)字符串的最小长度(可选参数,默认为4) 3) 字符串的最大长度(可选参数,默认为10)
这个程序既不使用内存也不做大量的 IO。我可以使用什么策略来增加单位时间内写入的字节数。
import random
import sys
K_SIZE = 1000
class Generator:
def __init__(self,low=4,high=10):
self.table = {i:chr(i) for i in range(33,127)}
self.low = low
self.high = high
def create_n_bytes(self,total_bytes):
bytes_created = 0
"""Hack at the moment, this condition will fail only after more than n bytes are
written """
while bytes_created < total_bytes:
bytes_to_create = random.randint(self.low,self.high)
bytes_created = bytes_created+bytes_to_create+1
word=[""]*bytes_to_create
for i in range(bytes_to_create):
word[i] = self.table[random.randint(33,126)]
text = "".join(word)
#print(str(hash(text))+"\t"+text)
print(text)
def get_file_size_from_command_line():
size = sys.argv[1]
return size
def get_min_word_len_from_command_line():
if len(sys.argv) > 2:
low = sys.argv[2]
return int(low)
def get_max_word_len_from_command_line():
if len(sys.argv) > 3:
high = sys.argv[3]
return int(high)
def get_file_size_in_bytes(size):
multiplier = 1
size_unit = size[-1]
if size_unit == 'M' or size_unit == 'm':
multiplier = K_SIZE*K_SIZE
elif size_unit == 'K' or size_unit == 'k':
multiplier = K_SIZE
elif size_unit == 'G' or size_unit == 'g':
multiplier = K_SIZE*K_SIZE*K_SIZE
elif size_unit in ('0','1','2','3','4','5','6','7','8','9'):
multiplier = 1
else:
print("invalid size")
exit()
total_bytes = 0
if multiplier == 1:
total_bytes = int(size)
else:
total_bytes = multiplier*int(size[:len(size)-1])
return total_bytes
def main():
if len(sys.argv) == 2:
gen = Generator()
elif len(sys.argv) == 3:
gen = Generator(get_min_word_len_from_command_line())
elif len(sys.argv) == 4:
gen = Generator(get_min_word_len_from_command_line(),get_max_word_len_from_command_line())
file_size = get_file_size_in_bytes(get_file_size_from_command_line())
gen.create_n_bytes(file_size)
if __name__== "__main__":
main()
【问题讨论】:
-
你在 linux / unix / OSX 上吗?为此目的,有一个特殊的文件 /dev/urandom。
-
你为什么要创建
word一个列表,然后将其全部加入以使其成为一个字符串?你正在做不必要的列表插入,你还需要一些argparse在这段代码中
标签: python performance