检查线程时间

时间:2017-05-25 13:50:27

标签: python multithreading python-multithreading

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

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)

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

1 个答案:

答案 0 :(得分: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)