Python 减少程序生成随机数据的运行时间
我需要生成10GB的随机数据 我编写了以下python脚本,通过将包含随机长度的可打印ASCII字符的字符串写入文件的每一行来生成所需的字节数 它需要3个命令行参数。 1) 大小 2) 字符串的最小长度(可选参数,默认为4) 3) 字符串的最大长度(可选参数,默认为10) 此程序既不使用内存也不执行大量IO。我可以使用什么策略来增加每单位时间写入的字节数Python 减少程序生成随机数据的运行时间,python,performance,Python,Performance,我需要生成10GB的随机数据 我编写了以下python脚本,通过将包含随机长度的可打印ASCII字符的字符串写入文件的每一行来生成所需的字节数 它需要3个命令行参数。 1) 大小 2) 字符串的最小长度(可选参数,默认为4) 3) 字符串的最大长度(可选参数,默认为10) 此程序既不使用内存也不执行大量IO。我可以使用什么策略来增加每单位时间写入的字节数 import random import sys K_SIZE = 1000 class Generator: def __ini
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()
随机导入
导入系统
K_尺寸=1000
类别生成器:
定义初始值(自,低=4,高=10):
self.table={i:chr(i)表示范围(33127)}
self.low=低
self.high=高
def创建字节(自身,总字节):
创建的字节数=0
“”“Hack目前,只有在超过n个字节的情况下,此条件才会失败。”
书面的
创建的字节数小于总字节数时:
字节到创建=random.randint(self.low,self.high)
bytes_created=bytes_created+bytes_to_create+1
word=[“”]*要创建的字节数
对于范围内的i(字节到创建):
word[i]=self.table[random.randint(33126)]
text=”“.join(word)
#打印(str(散列(文本))+“\t”+文本)
打印(文本)
从命令行()获取文件大小:
大小=系统argv[1]
返回大小
def从命令行()获取单词长度:
如果len(sys.argv)>2:
低=系统argv[2]
返回整数(低)
def从命令行()获取最大单词长度:
如果len(sys.argv)>3:
高=系统argv[3]
返回整数(高)
def get_文件大小(以字节为单位)(大小):
乘数=1
尺寸单位=尺寸[-1]
如果大小单位='M'或大小单位='M':
乘数=K_大小*K_大小
elif大小单位=='K'或大小单位=='K':
乘数=K_大小
elif大小单位=='G'或大小单位=='G':
乘数=K_大小*K_大小*K_大小
elif大小单位为('0','1','2','3','4','5','6','7','8','9'):
乘数=1
其他:
打印(“无效大小”)
退出()
总字节数=0
如果乘数=1:
总字节数=int(大小)
其他:
总字节数=乘数*int(大小[:len(大小)-1])
返回总字节数
def main():
如果len(sys.argv)==2:
发电机
elif len(系统参数)=3:
gen=生成器(从命令行()获取单词长度)
elif len(系统参数)=4:
gen=生成器(从命令行()获取最小单词长度,从命令行()获取最大单词长度)
文件大小=获取文件大小(以字节为单位)(从命令行()获取文件大小)
gen.create\u n\u字节(文件大小)
如果名称=“\uuuuu main\uuuuuuuu”:
main()
首先,如果您要生成纯ASCII,并且需要尽可能快,那么生成字节的速度可能会比str
快。如果需要,您可以随时对它们调用decode('ascii')
,但更简单的是,只需将它们直接写入sys.stdout.buffer
或sys.stdout.buffer.raw
这意味着您可以摆脱将数字映射到chr
值的表,只需从整数中构造一个bytes
或bytearray
。(只要所有的值都在范围(0,128)
,就可以保证得到相同的结果,但是一个函数调用中包含一个C循环,而不是Python循环中的函数调用。)
另外,您可以调用random.choices(范围(33127),k=N)
,然后将结果传递给bytes
构造函数,而不是构造一个由N个空字符串组成的列表,然后逐个替换它们
正如狄龙·戴维斯(Dillon Davis)所指出的那样,当我们处于这种状态时,randint
相当缓慢;通过手动执行相同的逻辑,您可以将速度提高3-5倍。这在这里并不重要(我们为几百个选择做了一个randint
),但仍然可以修复它
所以,把这些放在一起:
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 """
chars = range(33, 127)
while bytes_created < total_bytes:
bytes_to_create = int(random.random() * (high-low+1) + low)
word = bytes(random.choices(chars, k=bytes_to_create))
bytes_created = bytes_created+bytes_to_create+1
sys.stdout.buffer.write(word + b'\n')
# necessary if you're doing any prints between calls
sys.stdout.flush()
现在,如何将其分解为low
到high
字节的单词?我想不出有什么真正聪明的方法,但哑循环应该比上面所有代码都快:
i = 0
while i < len(buf) - self.high:
i += random.randint(self.low, self.high)
buf[i] = 10 # newline
sys.stdout.buffer.write(buf.data[:i])
这里的加速比对于1MB的数组应该比1000字节这样的小数组要大得多(由于额外的分配,对于绝对巨大的数组也可能不好),但它确实值得测试
性能比较在很大程度上取决于您的平台(包括您正在写入的终端,如果您没有重定向到/dev/null
或NUL
),以及您选择的参数
使用默认值low=4
,high=10
,和total_bytes=1000
(我使用1010
使NumPy失败),在我的笔记本电脑上运行(macOS,iTerm内的IPython,不重定向stdout,CPython 3.7.0和pypypy 3.5.2/5.10),以下是我的结果:
- 原始代码:2.7ms
- PyPy中的原始代码:938µs
- 带有
randint
的我的版本:911µs
- 我的随机版本:909µs
- 我的PyPy版本(无
random.choices
):799µs
- NumPy循环版本:584µs
- 只需写入预先存在的1000字节缓冲区:504µs
如果减去最后一个,得到不同算法的实际时间:
- 原始代码:2.2ms
- PyPy中的原始代码:434µs
- 带有
randint
的我的版本:407µs
- 我的随机版本:405µs
- 我的PyPy版本(不含
随机选项
):295µs
- NumPy循环版本:80µs
我使用的是另一台笔记本电脑,用于NumPyrandint
/cumsum
版本,但它是针对原始NumPy版本进行测试的,stdout重定向到/d
i = 0
while i < len(buf) - self.high:
i += random.randint(self.low, self.high)
buf[i] = 10 # newline
sys.stdout.buffer.write(buf.data[:i])
sizes = np.random.randint(self.low, self.high, total_bytes//self.low, dtype=np.int32)
offsets = np.cumsum(sizes)
last = np.searchsorted(offsets, 1000)
offsets = offsets[:last]
buf[offsets] = 10