首页 > 代码库 > 关于单线程写入文件测速

关于单线程写入文件测速

1. 文件总大小 69.8M

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. 生成如下格式:

[(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. 正则:

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

5.代码:

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.  总结: 

从上面数据来说  write 优势要大于 print 和writelines。

 

上面只是个人临时测试结果,并不能代表通用性。  如果问题欢迎指出


关于单线程写入文件测速