想法
用 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('{:.5%}'.format(os.path.getsize(fileName) / fileSize)) print() 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: 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() 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