python核心编程学习笔记-2016-08-28-01-习题18-4和习题18-9

习题18-4

#-*-coding: utf-8-*-

import time

char = chr(input("Enter a positive number from 0 to 255: "))
filename = raw_input("Enter a filename: ")

count = 0
time_start = time.clock()
with open(filename, 'r') as f:
for eachLine in f:
if eachLine == bin(ord(char)) + '\n':
count += 1
f.close()
time_end = time.clock()
print "%s occur %d time in %s." % (char, count, filename)
print "using", (time_end - time_start), 's'

counts = []
count = 0
for eachLine in text:
if eachLine == bin(ord(char)) + '\n':
count += 1
counts.append(count)

time_start = time.clock()
with open(filename, 'r') as f:
if (i + 1) * (len(text) / threadNum) <= len(text):
else:

f.close()
count = sum(counts)
time_end = time.clock()
print "%s occur %d time in %s." % (char, count, filename)
print "using", (time_end - time_start), 's'        

但是看结果

习题18-9

#-*-coding: utf-8-*-

import time

filenames = ['ex9-19.txt', 'ex9-19.txt', 'ex9-19.txt', 'ex9-19.txt', 'ex9-19.txt']
sin_counts = []
mul_counts = []
def countline(filename, counts):
f = open(filename, 'r')
count = 0
for eachLine in f:
count += 1
counts.append(count)

time_start = time.clock()
for i in range(len(filenames)):
countline(filenames[i], sin_counts)
time_end = time.clock()
print sin_counts
print time_end - time_start

time_start = time.clock()
for i in range(len(filenames)):

for i in range(len(filenames)):

for i in range(len(filenames)):

time_end = time.clock()
print mul_counts
print time_end - time_start
结果

单线程比多线程还要快。这个可能是由于这两个程序都是计算密集型的原因吧。具体原因暂时存疑吧，等到具备操作系统的基本知识后，或许就会明白了。

Python核心编程 第九章练习

2016-05-12 19:56:03

python核心编程答案（第十六章）

2014-07-27 16:15:31

Python核心编程v2.0 第11章习题答案

2017-09-06 17:03:32

python核心编程第三版课后习题一

2017-01-04 14:43:47

《Python核心编程(第二版)》练习题(自己写的)

2017-10-08 00:08:11

《python核心编程第二版》第五章练习解析

2015-04-25 10:05:15

《Python核心编程》第9章 习题

2015-11-22 21:00:53

Python核心编程（第三版）课后习题解答——第二章

2017-06-27 22:06:28

《Python核心编程》第11章 习题

2016-01-22 16:15:31

Python核心编程（第三版）课后习题解答——第四章

2017-07-05 22:48:18