Re: [問題] 如何優化迴圈的寫法

看板Python作者時間3年前 (2021/03/01 19:27), 3年前編輯推噓0(001)
留言1則, 1人參與, 3年前最新討論串3/3 (看更多)
參考一下 時間 3.5388457775115967 0.2786409854888916 0.00041604042053222656 0.00026702880859375 with open('138300.jpg', 'rb') as r, open("t3.txt", "wb") as w: w.write(r.read()[::-1]) ※ 引述《Schottky (順風相送)》之銘言: : ※ 引述《xji4y3ru (千眼萬雨)》之銘言: : : 我寫了一個把檔案的位元順序顛倒之後再生成新檔案的程式,用的主要是list跟while, : : 程式碼如下: : : ------------------------------------------- : : 檔案大小在100kb左右速度都還可以在數秒中完成,但是200kb就要十幾秒,500kb大約就 : : 要1分鐘。請問是不是因為這個寫法太笨了,浪費太多時間?有什麼可以優化的作法嗎? : 其實我覺得問題不是出在迴圈,而是 list 變大之後操作起來太緩慢 : 我寫了一個不用 list 的版本 : 先用 seek 和 tell 得知檔案大小以後,直接從檔案尾寫到檔案頭 : 照理說迴圈從兩個變一個,速度頂多是兩倍快,但快了大概幾十倍 : #!/usr/bin/env python3 : # : # Invert a file : # : import os : fin = open("pi-py.txt", "rb") : fout = open("output.txt", "wb") : fin.seek(0, 2) # Goto end : in_size = fin.tell() : fin.seek(0, 0) # Goto start : n = in_size-1 : while (n>=0): : ch = fin.read(1) : fout.seek(n, 0) : fout.write(ch) : n-=1 : fin.close() : fout.close() : ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆ : 後來又想到可以不用迴圈直接反轉字串的方法,速度更快 : #!/usr/bin/env python38 : # : # Invert a file : # : fin = open("pi-py.txt", "rb") : fout = open("output.txt", "wb") : fstr = fin.read() : fstr = fstr[::-1] : fout.write(fstr) : fin.close() : fout.close() -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.232.65.15 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1614598078.A.943.html ※ 編輯: LP9527 (118.232.65.15 臺灣), 03/01/2021 20:08:04

03/01 21:55, 3年前 , 1F
感謝~
03/01 21:55, 1F
文章代碼(AID): #1WFC--b3 (Python)
文章代碼(AID): #1WFC--b3 (Python)