2

有料のサードパーティAPIからリアルタイムデータを取得するPythonバックエンドWebサーバーに取り組んでいます。このAPIを非常に高速にクエリする必要があります(10秒あたり約150クエリ)。したがって、200個のスレッドを生成し、URLをキューに書き込む小さな概念実証を作成しました。次に、スレッドはキューのURLから読み取り、HTTPリクエストを送信します。サードパーティのAPIは、遅延と呼ばれる値を返します。これは、サーバーがリクエストを処理するのにかかった時間です。これは、すべてのURLを(繰り返しではなく)ダウンロードするだけのPOCコードです。

_http_pool = urllib3.PoolManager()

def getPooledResponse(url):
    return _http_pool.request("GET", url, timeout=30)

class POC:
    _worker_threads = []
    WORKER_THREAD_COUNT = 200
    q = Queue.Queue()

    @staticmethod
    def worker():
        while True:
            url = POC.q.get()
            t0 = datetime.datetime.now()
            r = getPooledResponse(item)
            print "thread %s took %d seconds to process the url (service delay %d)" % (threading.currentThread().ident, (datetime.datetime.now() - t0).seconds, getDelayFromResponse(r))
            POC.q.task_done()

    @staticmethod
    def run():
          # start the threads if we have less than the desired amount
          if len(POC._worker_threads) < POC.WORKER_THREAD_COUNT:
              for i in range(POC.WORKER_THREAD_COUNT - len(POC._worker_threads)):
                  t = threading.Thread(target=POC.worker)
                  t.daemon = True
                  t.start()
                  POC._worker_threads.append(t)

          # put the urls in the queue
          for url in urls:
              POC.q.put(url)
              # sleep for just a bit so that the requests don't get sent out together (this is a limitation of the API I am using)
              time.sleep(0.3)   
POC.run()

これを実行すると、最初のいくつかの結果が妥当な遅延で返されます。

thread 140544300453053 took 2 seconds to process the url (service delay 1.782)

ただし、約10〜20秒後に、次のようなものが表示されます。

thread 140548049958656 took 23 seconds to process the url (service delay 1.754)

つまり、サーバーが少し遅れて戻ってきても、スレッドの完了に時間がかかります...

残りの21秒の実行がどこで費やされているかを確認するにはどうすればよいですか?

ありがとう!

4

1 に答える 1

0

コードにはプロファイラーを使用する必要があります。

于 2012-05-16T22:17:49.153 に答える