關於單線程寫入文件測速

1. 文件總大小 69.8Mhtml

2. 文件內容格式以下: 測試

66.249.69.131 - - [10/Aug/2016:03:20:09 +0800] "GET /robots.txt HTTP/1.1" 404 162 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"

3. 生成以下格式:google

[('66.249.69.131', '10/Aug/2016:03:20:09 +0800', 'GET /robots.txt HTTP/1.1', '404', '162', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)')]

4. 正則:spa

matcher = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(.*)\] "(.*)" (\d+) (\d+) ".*" "(.*)"')

5.代碼:code

import re
import datetime
# matcher = re.compile(r'(?P<remote>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(?P<time>.*)\] "(?P<request>.*)" (?P<status>\d+) (?P<length>\d+) ".*" "(?P<ua>.*)"')
matcher = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(.*)\] "(.*)" (\d+) (\d+) ".*" "(.*)"')
fb = open('111','w+')
def filenum(fb):
    start = datetime.datetime.now()
    with open('access.log') as f:
        for fobj in f:
            # fb.write(str(re.findall(matcher,fobj)) + '\n')
            # fb.writelines(str(re.findall(matcher,fobj)) + '\n')
            print(str(re.findall(matcher,fobj)),file=fb)
        end = datetime.datetime.now()
    return (end-start).total_seconds()
public_time = filenum(fb)
fb.close()
print(public_time)
6. 測試結果(3 次測試結果):
  a) . write :   平均用時 4.9s
  b) . writelines :  只測試了一次,用時41s 果斷放棄
  c) . print  : 平均用時 5.22s 
 

7.  總結: htm

從上面數據來講  write 優點要大於 print 和writelines。

 

上面只是我的臨時測試結果,並不能表明通用性。  若是問題歡迎指出blog

相關文章
相關標籤/搜索