1 times = 24292128
2 def foo():
3 sum = 0
4 for i in range(10):
5 sum += 1
6 sum = 0
7
8 def useFoo():
9 foo()
10
11
12 def app1():
13 global times
14 for i in range(times):
15 foo()
16
17 def app2():
18 global times
19 for i in range(times):
20 useFoo()
21
22
23 app1()
24 app2()
25
1 self.infile.seek(0)
2 while True:
3 buf = self.infile.read(1000)
4 if buf == '':
5 break;
6 for c in buf:
7 if c in self.dict:
8 self.dict[c] += 1
9 else:
10 self.dict[c] = 0
这样类似与c++把函数inlie,但是python的动态特性使它不支持inline。可是这样处理如果以后在读文本,还要copy同样的code。不太好,
理想的情况我们的应用代码应该只是考虑每次读一个bytes,缓冲区的事情由其他地方写好的模块自动处理。
这样可读性维护性都比较好,直观,但是效率不能保证了,因为加入了函数调用。如果特别需要效率只能权衡了。 2.下面给出一个用iterator的实现,一个CharBufReader类,封装了buf,对外提供一次读取一个byte的接口(内部实现从buf读取,buf读完再fill buf)。
这样代码好复用。
因为提供next函数,所以可以用iterator访问。但是效率上很慢,和以前不优化,用file.read(1)差不多90s左右的时间。可以看出就是主要是因为
函数调用造成了原来程序速度慢。而不是因为不用自己写的缓冲读文件时间长。
1 class CharBufReader(object):
2 def __init__(self, mfile, bufSize = 1000):
3 self.mfile = mfile
4 #self.bufSize = 64 * 1024 #64k buf size
5 self.capacity = bufSize
6 self.buf = '' #buf of char
7 self.cur = len(self.buf)
8 self.size = len(self.buf)
9
10 def __iter__(self):
11 return self
12
13 def next(self):
14 if self.cur == self.size:
15 #if self.cur == len(self.buf):
16 #if self.cur == self.buf.__len__():
17 self.buf = self.mfile.read(self.capacity)
18 self.size = len(self.buf)
19 if self.size == 0:
20 raise StopIteration
21 self.cur = 0
22 self.cur += 1
23 return self.buf[self.cur - 1]
24
25
26 class Compressor():
27 def caculateFrequence(self):
28 """The first time of reading the input file and caculate each
29 character frequence store in self.dict
30 """
31 self.infile.seek(0)
32 reader = compressor.CharBufReader(self.infile)
33 for c in reader:
34 if c in self.dict:
35 self.dict[c] += 1
36 else:
37 self.dict[c] = 0 3.网上查了一下用generator可以避免函数调用的代价,于是试了下,generator易于实现,好用,可读性强。
但是速度嘛,还是不如第一种情况,但是比第2种情况和优化前的程序要快。大概55S。
1 def readChar(self):
2 while True:
3 buf = self.infile.read(1000)
4 if buf == '':
5 break
6 for c in buf:
7 yield c
8
9 def caculateFrequence(self):
10 """The first time of reading the input file and caculate each
11 character frequence store in self.dict
12 """
13 self.infile.seek(0)
14 reader = self.readChar()
15 for c in reader:
16 if c in self.dict:
17 self.dict[c] += 1
18 else:
19 self.dict[c] = 0
g