Skip to content

Instantly share code, notes, and snippets.

@bcherry
Created March 4, 2010 20:05
Show Gist options
  • Save bcherry/322060 to your computer and use it in GitHub Desktop.
Save bcherry/322060 to your computer and use it in GitHub Desktop.
var performance = (function () {
var my = {};
// Wrap a function body in this to return a copy that instruments itself
// If you want this to be useful, you should give your profiled function a name,
// otherwise it will be identified as "", which is less than useful.
my.profile = function (func) {
return function () {
var start = new Date().getTime(),
time,
retval = func.apply(this, Array.prototype.slice.call(arguments));
time = new Date().getTime() - start;
console.info("Call to function %o took %oms", func.name, time);
return retval;
};
};
// Use this to instrument chunks of code that are repeated frequently and tally the total
// running time.
// Ex: var profiler = performance.newProfiler("mycode");
// // some loop...
// profiler.begin("somesection");
// //... code
// profiler.end("somesection");
// // end loop
// profiler.report(true); // alerts total running time of the inner segment
my.newProfiler = function (name) {
var profiler = {},
start = new Date().getTime(),
profiles = {};
function newProfile() {
var profile = {},
total = 0,
last;
profile.getTotal = function () {
return total;
};
profile.start = function () {
last = new Date().getTime();
};
profile.stop = function () {
total += new Date().getTime() - last;
};
return profile;
}
profiler.begin = function (section) {
if (!(section in profiles)) {
profiles[section] = newProfile();
}
profiles[section].start();
};
profiler.end = function (section) {
if (!section in profiles) {
console.error("Profiler: profile %s not found", section);
}
profiles[section].stop();
};
profiler.report = function (useAlert) {
var key,
profile,
total = 0,
report = ["Results for profiler " + name + ":"],
i,
l;
for (key in profiles) {
profile = profiles[key];
total += profile.getTotal();
report.push("Section " + key + " " + profile.getTotal() + "ms");
}
report.push("Total: " + total + "ms");
if (useAlert) {
alert(report.join("\n"));
} else {
for (i = 0, l = report.length; i < l; i++) {
console.info(report[i]);
}
}
};
return profiler;
};
return my;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment