1
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()
4

1 に答える 1

2

への呼び出しは.tell()、私にとって物事を大幅に遅くします。python-space にどれだけ書き込まれたかを追跡すると、時間を 10 分の 1 に短縮できます。

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"
于 2013-05-17T15:14:48.513 に答える