Skip to content

Instantly share code, notes, and snippets.

@muratpurc
Created March 9, 2012 22:12
Show Gist options
  • Save muratpurc/2008994 to your computer and use it in GitHub Desktop.
Save muratpurc/2008994 to your computer and use it in GitHub Desktop.
JS: Simple JavaScript profiler
/**
* Simple profiler, used to measure time taken by processes.
* Usage:
* <pre>
* var profile = new mpProfiler("Measuring async loop");
* i;
* for (i = 0; i < 10; i++) {
* // do something really cpu expensive
* doExpensiveJob(i, 10, function(pos, total){
* profile.addStep("Step " + cur + " from " + total + " done!");
* if (pos === total) {
* // the end is reached
* var results = profile.end();
* // dump the results containg detailed measurement infoes
* console.log(results);
* }
* });
* }
* </pre>
*
* @class mpProfiler
* @constructor
* @param {String} [msg=""]
*/
var mpProfiler = function(msg) {
this.start(msg);
};
/**
* Starts a timer.
* @method start
* @param {String} [msg=""] Description of started timer
*/
mpProfiler.prototype.start = function(msg) {
this._msg = msg || "";
this._start = new Date().getTime();
this._end = null;
this._diffTotal = null;
this._steps = [];
};
/**
* Add a step to a specific timer.
* @method addStep
* @param {String} [msg=""] Description of the step
* @return {Object} Containing details about the timer step.
*/
mpProfiler.prototype.addStep = function(msg) {
msg = msg || "";
var start = new Date().getTime(),
lenSteps = this._steps.length,
diff = 0, diffTotal = start - this._start,
curStep;
if (lenSteps > 0) {
diff = start - this._steps[lenSteps-1].start;
}
curStep = {
start: start,
msg: msg,
diff: diff,
diffTotal: diffTotal
};
this._steps.push(curStep);
return curStep;
};
/**
* Ends a running timer and returns all collected results.
* @method end
* @param {Boolean} [flush=false] Flag to flush results to logger (console.log, if available)
* @return {Object} Containing details about the timer including all steps.
*/
mpProfiler.prototype.end = function(flush) {
flush = flush || false;
var end = new Date().getTime(),
result = {};
this._end = end;
this._diffTotal = end - this._start;
result = {
msg: this._msg,
start: this._start,
end: this._end,
diffTotal: this._diffTotal,
steps: this._steps
};
if (flush) {
if ("undefined" !== typeof console) {
console.log("mpProfiler result", result);
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment