【发布时间】:2019-03-11 12:33:06
【问题描述】:
我正在运行一个 python 脚本,该脚本调用一个依赖于慢速 api 的函数,该函数又调用另一个也依赖于相同慢速 api 的函数。我想加快速度。
最好的方法是什么?线程模块?如果有,请举例说明。我注意到关于线程的一件事是,您似乎无法从线程中检索返回值……而且我的大部分脚本都是为了打印函数的返回值而编写的……
这是我试图提高 I/O 性能的代码
def get_price_eq(currency, rate):
if isAlt(currency) == False:
currency = currency.upper()
price_eq = 'btc_in_usd*USD_in_'+str(currency)+'*'+str(rate)
#print price_eq
return price_eq
else:
currency = currency.lower()
price_eq = 'poloniex'+ str(currency) + '_close' + '*' + str(rate)
print(price_eq)
return price_eq
def get_btcprice_fiat(price_eq):
query = '/api/equation/'+price_eq
try:
conn = api.hmac(hmac_key, hmac_secret)
btcpricefiat = conn.call('GET', query).json()
except requests.exceptions.RequestException as e: # This is the correct syntax
print(e)
return float(btcpricefiat['data'])
usdbal = float(bal) * get_btcprice_fiat(get_price_eq('USD', 1))
egpbal = float(bal) * get_btcprice_fiat(get_price_eq('EGP', 1))
rsdbal = float(bal) * get_btcprice_fiat(get_price_eq('RSD', 1))
eurbal = float(bal) * get_btcprice_fiat(get_price_eq('EUR', 1))
如你所见,我调用了 get_btc_price,它从数据供应商处调用了一个慢速 api,并传入了另一个函数的结果,该函数使用了另一个 api 调用,我做了 4 次以上,我正在寻找增加的方法在这个功能上的表现?另外,我读过的一件事是你不能从线程中获得返回值?我的大部分代码都返回值,然后我打印给用户,我该如何处理?
【问题讨论】:
-
不要假设使用线程会神奇地让你的程序更快。编写正确的多线程应用程序并非易事。您能否改为通过一次 API 调用来获取所有必需的信息?
-
线程仅在您的进程受 I/O 限制且等待其他 API 调用完成时才有帮助。但是,如果您的进程受 CPU 限制(即处理数字),那么线程将无济于事。
标签: python python-3.x multithreading python-2.7