Как ускорить время выполнения скрипта приложений Google - PullRequest
0 голосов
/ 20 февраля 2020

Этот сценарий обрабатывает 3 CSV-файла из потоков GMAIL, время выполнения было быстрым, пока я не добавил часть регулярного выражения, ищущую в теле

tmp = truncatedContent.match(/Date Tripped:\s*([:\w\s]+)\r?\n/);
tmp = truncatedContent.match(/Business Date:\s([\w\s]+\(\w+\))/);

С добавлением этой части сценарий завершается успешно, но теперь для завершения требуется приблизительно 17 секунд, а не 4 секунды.

Я полагаю, что здесь есть неэффективность, требующая руководства:

function SLSalesImportFromGmail() {
  var ss = SpreadsheetApp.getActive(); // Get the spreadsheet file once

  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
  if (threads && threads.length > 0) {
    var message = threads[0].getMessages()[0];
    // Get the first email message of a threads
    var content = message.getPlainBody();
    var tmp,
    truncatedContent = content.match(/^([^\r\n]+\r?\n){5}/)[0];
    // Get the plain text body of the email message
    // You may also use getRawContent() for parsing HTML
    // Implement Parsing rules using regular expressions
    if (truncatedContent) {

      tmp = truncatedContent.match(/Date Tripped:\s*([:\w\s]+)\r?\n/);
      var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

      tmp = truncatedContent.match(/Business Date:\s([\w\s]+\(\w+\))/);
      var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';
    // Get all of the attachments and loop through them.
    var attachments = message.getAttachments(); 
    for (var i = 0; i < attachments.length; i++) {
      var attachment = attachments[i];
      var title = attachment.getName();

      // Is the attachment a CSV file
      attachment.setContentTypeFromExtension();
      var table = Utilities.parseCsv(attachment.getDataAsString());
      if (attachment.getContentType() === "text/csv") {
        switch (title) { // Update the specified sheets
          case "Sales.csv":
            /**
            * Clears the sheet of values & formatting and inserts the new table 
            * using the Apps Script built-in CSV parser.
            * @param {string} sheetName - The name of the sheet to update
            * @returns {undefined}
            */
            ss.getSheetByName("South Loop Sales").getRange("A:M").clear();
            ss.getSheetByName("South Loop Sales").getRange(1, 1, table.length, table[0].length).setValues(table);
            ss.getSheetByName("South Loop Sales").appendRow(['Last Sync:', tripped]);
            ss.getSheetByName("South Loop Sales").appendRow(['POS Date:', businessdate]);
            break;
          case "Labor.csv":
            ss.getSheetByName("South Loop Labor").getRange("A:M").clear();
            ss.getSheetByName("South Loop Labor").getRange(1, 1, table.length, table[0].length).setValues(table);
            break;
          case "ServerPerformance.csv":
            ss.getSheetByName("South Loop Servers").getRange("A:M").clear();
            ss.getSheetByName("South Loop Servers").getRange(1, 1, table.length, table[0].length).setValues(table);            
            break;
        }
      }      
    }
    if( message.getSubject().indexOf('END OF DAY') !== -1) {
    SLlogTodaysSales();
    SLlogTodaysServers();
    }
    if( message.getSubject().indexOf('END OF WEEK') !== -1) {
    SLlogTodaysSales();
    SLlogTodaysServers();
    SLlogWeeksLabor();
    }
    }
    //marks the Gmail message as read, unstars it and deletes it using Gmail API (Filter sets a star)
  message.markRead();
  message.unstar();
  Gmail.Users.Messages.remove("me", message.getId()); // Added
  }
}

function SLlogTodaysSales() {
  var todaysSales = SpreadsheetApp.getActive().getRange('South Loop Sales Log!SLSalesImport');
  var logSheet = todaysSales.getSheet();
  logSheet.appendRow(
    todaysSales.getValues()
    .reduce(function(a, b) { return a.concat(b); }) // flatten the 2D array to 1D
  );
}
function SLlogWeeksLabor() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('South Loop Labor Log');
  var rg=sh.getRange('SLLaborImport');
  var vA=rg.getValues();
  sh.getRange(sh.getLastRow()+1,1,vA.length,vA[0].length).setValues(vA);
}
function SLlogTodaysServers() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('South Loop Server Log');
  var rg=sh.getRange('SLServerReport');
  var vA=rg.getValues();
  sh.getRange(sh.getLastRow()+1,1,vA.length,vA[0].length).setValues(vA);
}

Стенограмма выполнения, похоже, она застревает на appendRow для по какой-то причине .:

[20-02-20 13:37:31:218 CST] SpreadsheetApp.getActive() [0 seconds]
[20-02-20 13:37:31:420 CST] GmailApp.getUserLabelByName([Sundance Square]) [0.2 seconds]
[20-02-20 13:37:31:569 CST] GmailApp.GmailLabel.getThreads([0, 1]) [0.149 seconds]
[20-02-20 13:37:31:712 CST] GmailApp.GmailThread.getMessages() [0.141 seconds]
[20-02-20 13:37:31:952 CST] GmailApp.GmailMessage.getPlainBody() [0.24 seconds]
[20-02-20 13:37:31:958 CST] GmailApp.GmailMessage.getAttachments() [0.002 seconds]
[20-02-20 13:37:31:958 CST] GmailApp.GmailAttachment.getName() [0 seconds]
[20-02-20 13:37:31:959 CST] GmailApp.GmailAttachment.setContentTypeFromExtension() [0 seconds]
[20-02-20 13:37:32:122 CST] GmailApp.GmailAttachment.getDataAsString() [0.163 seconds]
[20-02-20 13:37:32:123 CST] Utilities.parseCsv([Sales

Order Status:,"All"
Report By:,"User closed"
Date Range:,"Current day (20 Feb 2020)"
Time Range:,"All day"

Void Totals
Amount,Quantity
12.0000,4

Financial Summary
Summary,Net Sal...) [0 seconds]
[20-02-20 13:37:32:123 CST] GmailApp.GmailAttachment.getContentType() [0 seconds]
[20-02-20 13:37:32:270 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Sales]) [0.146 seconds]
[20-02-20 13:37:32:271 CST] SpreadsheetApp.Sheet.getRange([A:M]) [0 seconds]
[20-02-20 13:37:32:272 CST] SpreadsheetApp.Range.clear() [0 seconds]
[20-02-20 13:37:32:272 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Sales]) [0 seconds]
[20-02-20 13:37:32:273 CST] SpreadsheetApp.Sheet.getRange([1, 1, 106, 8]) [0 seconds]
[20-02-20 13:37:32:281 CST] SpreadsheetApp.Range.setValues([[[Sales, , , , , , , ], [, , , , , , , ], [Order Status:, All, , , , , , ], [Report By:, User closed, , , , , , ], [Date Range:, Current day (20 Feb 2020), , , , , , ], [Time Range:, All day, , , , ,...) [0.007 seconds]
[20-02-20 13:37:32:282 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Sales]) [0 seconds]
[20-02-20 13:37:41:723 CST] SpreadsheetApp.Sheet.appendRow([[Last Sync:, 20 Feb 2020 1:36 PM]]) [9.44 seconds]
[20-02-20 13:37:41:868 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Sales]) [0.144 seconds]
[20-02-20 13:37:43:457 CST] SpreadsheetApp.Sheet.appendRow([[POS Date:, 20 Feb 2020 (Open)]]) [1.588 seconds]
[20-02-20 13:37:43:457 CST] GmailApp.GmailAttachment.getName() [0 seconds]
[20-02-20 13:37:43:458 CST] GmailApp.GmailAttachment.setContentTypeFromExtension() [0 seconds]
[20-02-20 13:37:43:624 CST] GmailApp.GmailAttachment.getDataAsString() [0.165 seconds]
[20-02-20 13:37:43:624 CST] Utilities.parseCsv([Labor

Date Range:,"Current week (17 Feb 2020 to 23 Feb 2020)"
Time Range:,"All day"

User Shifts
User,Job,Date In,Date Out,Reg Hrs,Rate,Reg Amt,OT Hrs,OT Rate,OT Amt,Total
Hazel Castillo,03-K...) [0 seconds]
[20-02-20 13:37:43:625 CST] GmailApp.GmailAttachment.getContentType() [0 seconds]
[20-02-20 13:37:43:716 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Labor]) [0.09 seconds]
[20-02-20 13:37:43:716 CST] SpreadsheetApp.Sheet.getRange([A:M]) [0 seconds]
[20-02-20 13:37:43:717 CST] SpreadsheetApp.Range.clear() [0 seconds]
[20-02-20 13:37:43:718 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Labor]) [0 seconds]
[20-02-20 13:37:43:718 CST] SpreadsheetApp.Sheet.getRange([1, 1, 71, 11]) [0 seconds]
[20-02-20 13:37:43:725 CST] SpreadsheetApp.Range.setValues([[[Labor, , , , , , , , , , ], [, , , , , , , , , , ], [Date Range:, Current week (17 Feb 2020 to 23 Feb 2020), , , , , , , , , ], [Time Range:, All day, , , , , , , , , ], [, , , , , , , , , , ], [Us...) [0.006 seconds]
[20-02-20 13:37:43:726 CST] GmailApp.GmailAttachment.getName() [0 seconds]
[20-02-20 13:37:43:727 CST] GmailApp.GmailAttachment.setContentTypeFromExtension() [0 seconds]
[20-02-20 13:37:44:037 CST] GmailApp.GmailAttachment.getDataAsString() [0.31 seconds]
[20-02-20 13:37:44:037 CST] Utilities.parseCsv([ServerPerformance

Order Status:,"All"
Report By:,"User closed"
Service Types:,"Table Service"
Date Range:,"Current day (20 Feb 2020)"
Time Range:,"All day"

Sales by User, Cost Center, Segme...) [0 seconds]
[20-02-20 13:37:44:038 CST] GmailApp.GmailAttachment.getContentType() [0 seconds]
[20-02-20 13:37:44:038 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Servers]) [0 seconds]
[20-02-20 13:37:44:039 CST] SpreadsheetApp.Sheet.getRange([A:M]) [0 seconds]
[20-02-20 13:37:44:039 CST] SpreadsheetApp.Range.clear() [0 seconds]
[20-02-20 13:37:44:039 CST] SpreadsheetApp.Spreadsheet.getSheetByName([Sundance Square Servers]) [0 seconds]
[20-02-20 13:37:44:040 CST] SpreadsheetApp.Sheet.getRange([1, 1, 36, 13]) [0 seconds]
[20-02-20 13:37:44:044 CST] SpreadsheetApp.Range.setValues([[[ServerPerformance, , , , , , , , , , , , ], [, , , , , , , , , , , , ], [Order Status:, All, , , , , , , , , , , ], [Report By:, User closed, , , , , , , , , , , ], [Service Types:, Table Service, ...) [0.003 seconds]
[20-02-20 13:37:44:044 CST] GmailApp.GmailMessage.getSubject() [0 seconds]
[20-02-20 13:37:44:044 CST] GmailApp.GmailMessage.getSubject() [0 seconds]
[20-02-20 13:37:44:380 CST] GmailApp.GmailMessage.markRead() [0.336 seconds]
[20-02-20 13:37:44:695 CST] GmailApp.GmailMessage.unstar() [0.314 seconds]
[20-02-20 13:37:44:697 CST] GmailApp.GmailMessage.getId() [0 seconds]
[20-02-20 13:37:48:477 CST] Execution succeeded [13.821 seconds total runtime]

1 Ответ

0 голосов
/ 21 февраля 2020

Переключение из .appendRow в .getRange / .setValue. Изменить:

            ss.getSheetByName("South Loop Sales").appendRow(['Last Sync:', tripped]);
            ss.getSheetByName("South Loop Sales").appendRow(['POS Date:', businessdate]);

на:

            ss.getSheetByName("South Loop Sales").getRange("C2").setValue(tripped);
            ss.getSheetByName("South Loop Sales").getRange("C1").setValue(businessdate);
...