LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Sunday, March 29, 2020

UrlFetchApp.fetchAllを使って複数のfetchを同時にやって実行時間の短縮を試みる


今回やること
  • UrlFetchApp.fetchAllを試してみる


fetchとfetchAllを比較してみる。
  • それぞれに同じ数のリクエストを送って速度を比較してみる


Google Books APIで任意のキーワードを決めて40件の結果を出力してみる。

今回使うキーワード
  • API
  • Google
  • Chrome

仮説
  • fetchallは並列で処理してくれて、fetch1回分の処理時間で実行できるだろう


検証してみます


UrlFetchApp.fetch
で1つずつ処理する場合

コード.gs
function getBooksFetch() {
  getBooksWithParams1();
  getBooksWithParams2();
  getBooksWithParams3();
}

function getBooksWithParams1() {
  var url = 'https://www.googleapis.com/books/v1/volumes?q=intitle:API&country=JP&langRestrict=ja&maxResults=40&orderBy=newest';
  var json = UrlFetchApp.fetch(url);
  Logger.log(json)
}

function getBooksWithParams2() {
  var url = 'https://www.googleapis.com/books/v1/volumes?q=intitle:Google&country=JP&langRestrict=ja&maxResults=40&orderBy=newest';
  var json = UrlFetchApp.fetch(url);
  Logger.log(json)
}

function getBooksWithParams3() {
  var url = 'https://www.googleapis.com/books/v1/volumes?q=intitle:Chrome&country=JP&langRestrict=ja&maxResults=40&orderBy=newest';
  var json = UrlFetchApp.fetch(url);
  Logger.log(json)
}


結果をログで見ると1.769秒



UrlFetchApp.fetchAll
で同時に複数処理する場合

コード2.gs
function getBooksFetchAll() {
  var url1 = 'https://www.googleapis.com/books/v1/volumes?q=intitle:API&country=JP&langRestrict=ja&maxResults=40&orderBy=newest';
  var url2 = 'https://www.googleapis.com/books/v1/volumes?q=intitle:Google&country=JP&langRestrict=ja&maxResults=40&orderBy=newest';
  var url3 = 'https://www.googleapis.com/books/v1/volumes?q=intitle:Chrome&country=JP&langRestrict=ja&maxResults=40&orderBy=newest';
  var response = UrlFetchApp.fetchAll([url1, url2, url3]);
  Logger.log(response);
}


getBooksFetchAllを実行した結果は0.929秒


結果

今回の検証データでは仮説には及びませんでした。
しかし、約半分くらいの処理時間になりました。

もっと重たい処理を試すと、Googleのサーバに負荷をかけてしまうと思うのでここではやりませんが、今回のような軽くて3つくらいの処理でも確実にfetchAllの方が処理が早いことがわかりました。

同時処理数の上限についてリファレンスに記載が見つけられませんでしたが、QuotasにあるプランごとのURL Fetch callsがそれにあたるかもしれません。


補足

ちなみに認証が必要なAPIをたたく場合はこのように書くと実行できました。

コード3.gs
function getBooksFetchAll() {
  var request1 = {
    'url': 'https://foobar',
    'method' : 'get',
    'contentType': "application/json", 
    'headers': {"Authorization": " Basic " + TOKEN}
  }

  var request2 = {
    'url': 'https://hogefuga',
    'method' : 'get',
    'contentType': "application/json", 
    'headers': {"Authorization": " Bearer " + TOKEN}
  }
  UrlFetchApp.fetchAll([request1, request2]);
}


Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...