检查线程时间



我刚刚学习了多线程,并从一些教程中获得了以下代码:

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)

有人可以告诉我如何找到相同的时间吗?

如果要

对整体执行进行计时:

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)

最新更新