gpt4 book ai didi

Python 使用 cProfile 优化 cose

转载 作者:行者123 更新时间:2023-12-01 05:44:23 24 4
gpt4 key购买 nike

def create_file_numbers_old(filename, size):
start = time.clock()
value = 0
with open(filename, "w") as f:
while f.tell()< size:
f.write((str(value))+'\n')
value += 1

end = time.clock()
print "time taken to write a file of size", size, " is ", (end -start), "seconds \n"

这就是我需要优化的功能!有人可以帮我在大约 3-4 秒内运行它吗?

def main(argv = sys.argv):
#add argument checking and parsing here ..

fpath = output_path(r"est.txt")
size=50*1024*1024 #write a 50M file
cProfile.run("create_file_numbers_old('%s', %d)" %(fpath, size))
fpath1 = output_path(r"est1.txt")
cProfile.run("create_file_numbers_new('%s', %d)" %(fpath1, size))


if __name__ == "__main__":
main()

最佳答案

.tell() 的调用对我来说显着减慢了速度。如果您跟踪 python-space 中写入了多少内容,则可以将时间减少 10 倍。

def create_file_numbers_old(filename, size):
start = time.clock()
value = 0
written = 0 # number of bytes written so far
with open(filename, "w") as f:
while written < size:
s = str(value) + '\n'
written += len(s) # add how many bytes are in this write()
f.write(s)
value += 1

end = time.clock()
print "time taken to write a file of size", size, " is ", (end -start), "seconds \n"

关于Python 使用 cProfile 优化 cose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16612075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com