2017-05-25 61 views
0

我剛剛瞭解多線程,並得到一些教程下面的代碼:檢查線程時間

import urllib2 
from multiprocessing.dummy import Pool as ThreadPool 

urls = [ 
    'http://www.python.org', 
    'http://www.python.org/about/', 
    'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html', 
    'http://www.python.org/doc/', 
    'http://www.python.org/download/', 
    'http://www.python.org/getit/', 
    'http://www.python.org/community/', 
    'https://wiki.python.org/moin/', 
    ] 

# open the urls in their own threads and return the results 
with Pool(4) as pool: 
    results = pool.map(urllib2.urlopen, urls) 

有人能告訴我怎麼做,我發現採取相同的時間?

回答

2

如果你想不想來一次整體執行:

import sys 
import time 
import urllib2 
from multiprocessing.dummy import Pool as ThreadPool 

get_timer = time.clock if sys.platform == "win32" else time.time # precision fix 

urls = ['http://www.python.org', 'http://www.python.org/about/'] # etc. 

start_time = get_timer() 
with ThreadPool(4) as pool: 
    results = pool.map(urllib2.urlopen, urls) 
print("Total execution time: {}s".format(get_timer() - start_time)) 

如果要單獨計時您的線程/進程,您應該創建自己的功能,收集起始時間開始,計算後的增量執行和地圖,而不是urllib2.urlopen,例如:

import sys 
import time 
import urllib2 
from multiprocessing.dummy import Pool as ThreadPool 

get_timer = time.clock if sys.platform == "win32" else time.time # precision fix for Windows 

urls = ['http://www.python.org', 'http://www.python.org/about/'] # etc. 

def timed_function(url): 
    start_time = get_timer() 
    result = urllib2.urlopen(url) 
    print("Thread finished in {}s for url: {}".format(get_timer() - start_time, url)) 
    return result 

with ThreadPool(4) as pool: 
    results = pool.map(timed_function, urls)