Python 生成无意义的大文件
2021-04-25 17:40:00

想法

用 Python 追加输入文件,如果文件达到指定的大小,则停止,否则继续。

代码

单线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import os, time

# 文件大小
fileSize = 52428800
# 文件名
fileName = "50MB.file"
# 开始计时
start = time.time()

def write_string():
# 追加文件内容
with open(fileName, 'a') as f:
f.write("@!#---50MiB Test File---#!@"+ "\r\n")

# 如果没有文件,先生成
if os.path.exists(fileName) != True:
with open(fileName, 'a') as f:
f.write("@!#--- Start ---#!@" + "\r\n")

while True:
# 如果已经大于或等于预定的大小,停止循环
if os.path.getsize(fileName) >= fileSize:
break
write_string()
# print(os.path.getsize("100MB.file") / fileSize)
# 获得文件进度,防止枯燥的等待
print('{:.5%}'.format(os.path.getsize(fileName) / fileSize))
print()
# Windows 改为 `cls`
os.system("clear")

end = time.time()
# 获取所用时间
print("共使用 {} 秒生成文件".format(end-start))

多线程

单线程的速度挺慢的,于是乎,可以用 threading 库实现多线程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import threading, os, time

# 文件大小
fileSize = 52428800
# 文件名称
fileName = "50MB.file"
# 开始计时
start = time.time()

def write_string():
# 追加文件
with open(fileName, 'a') as f:
# 这里现将 文本 * 100000 遍后再输出,可以提高速度与效率,但会造成偏差。
f.write("@!#---50MiB Test File---#!@"*100000 + "\r\n")

# 如果没有文件,先生成
if os.path.exists(fileName) != True:
with open(fileName, 'a') as f:
f.write("@!#--- Start ---#!@" + "\r\n")

while True:
# 如果已经大于或等于预定的大小,停止循环
if os.path.getsize(fileName) >= fileSize:
break
# 设定线程
thread1 = threading.Thread(target=write_string)
thread2 = threading.Thread(target=write_string)
thread3 = threading.Thread(target=write_string)
thread4 = threading.Thread(target=write_string)
# 启动线程
thread1.start()
thread2.start()
thread3.start()
thread4.start()
# 加入线程
thread1.join()
thread2.join()
thread3.join()
thread4.join()
# 获得文件进度,防止枯燥的等待
print('{:.5%}'.format(os.path.getsize(fileName) / fileSize))
print()
# Windows 改为 `cls`
os.system("clear")

end = time.time()
# 获取所用时间
print("共使用 {} 秒生成文件".format(end-start))

使用多线程的方法,据测试 生成 50MB 的文件大约需 0.3326 秒,生成 1GB 的文件需 9.5763 秒,此数据因电脑而异。

我也把这些文件放到了 百度网盘 Onedrive 里,你可以直接下载。

链接:https://drive.yfun.top/Test/File/

多线程下载链接示例:https://drive.yfun.top/Test/File/50MB.file