Skip to content

Instantly share code, notes, and snippets.

@vicc
Last active January 21, 2016 05:59
Show Gist options
  • Save vicc/31890b81f68278d76b68 to your computer and use it in GitHub Desktop.
Save vicc/31890b81f68278d76b68 to your computer and use it in GitHub Desktop.
Timer Module to easily log execution times for functions, promises, etc. on Parse Cloud Code
/*
The Timer Module makes it easy to analyze how long each
of your functions, promises, etc. are taking in Cloud
Code.
Although NSDate.getTime() isn't as accurate as other modern
approaches (e.g console.time, performance.now) it is still
quite helpful.
Author: Vicc Alexander
2015 © Vicc Alexander. All Rights Reserved.
*/
//Initialize a dictionary to store our timers
var timers = {};
//Function to start a timer
exports.time = function time(name) {
//Start timing
timers[name] = new Date().getTime();
}
//Function to end a timer
exports.endTime = function endTime(name) {
//End timer
var endTime = new Date().getTime();
//Retrieve start value to determine total time
if (timers[name]) {
//Retrieve start time
var startTime = timers[name];
//Calculate total execution time (in seconds)
var totalTime = (endTime - startTime)/1000;
//Log Time
console.log('Execution time for ' + name + ': ' + totalTime + " seconds.");
} else {
//Log Error
console.log("OOPS! Execution time for " + name + " could not be calculated. Make sure the name parameter matches the name parameter you used when you started the timer.")
}
}
@vicc
Copy link
Author

vicc commented Nov 11, 2015

Timer Module by Vicc Alexander

Getting Started

  1. Import timerModule.js into your cloud folder.
  2. As an example, say you wanted to use this in a script called myScript.js, all you have to do is:
//myScript.js

//Step 1. Import Module
var timer = require("cloud/timerModule.js");

Parse.Cloud.define("myFunction", function(request, response) {

    //Step 2. Start a timer and give it a name
    timer.time("myFunctionTimer");

    //Do Something Here!

    //Step 3. Stop the timer with a given name
    timer.endTime("myFunctionTimer");
});

Note: The name parameter allows you to run multiple timers simultaneously. Just remember that the .endTime() method always logs a message, and according to Parse, cloud functions may only log up to 100 messages per request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment