我已经构建了以下用于使用google的地方api获取电话号码的小程序,但它很慢.当我用6个项目进行测试时,它需要从4.86秒到1.99秒,我不确定为什么会发生重大变化.我对API很新,所以我甚至不确定哪些事情可以/不能加速,哪些事情留给服务于API的网络服务器以及我可以改变自己.
import requests,json,time
searchTerms = input("input places separated by comma")
start_time = time.time() #timer
searchTerms = searchTerms.split(',')
for i in searchTerms:
r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY')
a = r1.json()
pid = a['results'][0]['place_id']
r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY')
b = r2.json()
phone = b['result']['formatted_phone_number']
name = b['result']['name']
website = b['result']['website']
print(phone+' '+name+' '+website)
print("--- %s seconds ---" % (time.time() - start_time))
Run Code Online (Sandbox Code Playgroud)
您可能希望并行发送请求.Python提供了multiprocessing适合这样的任务的模块.
示例代码:
from multiprocessing import Pool
def get_data(i):
r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY')
a = r1.json()
pid = a['results'][0]['place_id']
r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY')
b = r2.json()
phone = b['result']['formatted_phone_number']
name = b['result']['name']
website = b['result']['website']
return ' '.join((phone, name, website))
if __name__ == '__main__':
terms = input("input places separated by comma").split(",")
with Pool(5) as p:
print(p.map(get_data, terms))
Run Code Online (Sandbox Code Playgroud)
使用会话来启用持久的 HTTP 连接(这样你就不必每次都建立一个新的连接)
大多数时间都没有花在计算您的请求上。时间花在与服务器的通信上。那是你无法控制的事情。
但是,您可以使用并行化来加快速度。为每个请求创建一个单独的线程作为开始。
from threading import Thread
def request_search_terms(*args):
#your logic for a request goes here
pass
#...
threads = []
for st in searchTerms:
threads.append (Thread (target=request_search_terms, args=(st,)))
threads[-1].start()
for t in threads:
t.join();
Run Code Online (Sandbox Code Playgroud)
然后随着请求数量的增长使用线程池,这将避免重复创建线程的开销。
| 归档时间: |
|
| 查看次数: |
14578 次 |
| 最近记录: |