#This program reads and writes 1k data to the same files 10000.
import threading
import time
def read_write_file(thread_num):
wf_name= "w_" + str(thread_num) + ".txt"
for i in range(0,10000):
try:
fd= open("1k.txt","r+")
w_fd= open(wf_name,"wb")
str1= fd.read(1024)
w_fd.write(str1)
fd.close()
except:
print "Error: I/O Exception"
def threads_start(num):
threads=dict()
try:
for index in range(num):
threads[index]= threading.Thread(target=read_write_file,args=(index,))
threads[index].start()
for i in range(0,4):
threads[i].join()
except:
print "Error: problem in running threads"
start_time= time.time()
threads_start(4)
print time.time() - start_time, " Seconds"
上述代码在虚拟机中比在本机系统中运行得更快。根据我的理解,由于开销,它应该比本机系统慢。为什么它更快?