Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Package Definition //
- var Package = {
- NAME: 'Profiler',
- VERSION: 0.1,
- DEFAULT: ['addProfiling', 'removeProfiling', 'profileReport'],
- EXPORT: [ ],
- EXPORT_OK: ['_start','_stop','_init'],
- EXPORT_TAGS: { }
- };
- // Private Variables //
- var _fnlist = {};
- /**
- * Create a tracking object for a new function
- * to be profiled.
- * @function
- */
- function _init(fname, fn, scope) {
- console.log("Adding " + fname + ": ");
- if (typeof _fnlist[fname] == 'undefined') {
- _fnlist[fname] = {
- fn: fn, // save original function
- scope: scope, // object owner of function (context)
- ncalls: 0, // number of calls made
- calls: {} // individual call profiling
- };
- }
- else
- throw new Error(fname + " is already being profiled");
- }
- /**
- * Start timing this function, run prior to the
- * actual function's execution.
- * @function
- */
- function _start(fname, fn, args) {
- _fnlist[fname].ncalls++;
- var start = new Date().getTime();
- var id = start + "_" + _fnlist[fname].ncalls;
- _fnlist[fname].calls[id] = {
- start: start,
- stop: null,
- args: args,
- total: 0
- };
- return id; // unique id for *this* call
- }
- /**
- * Stop timing a function and calculate total
- * elapsed time (milliseconds)
- * @function
- */
- function _stop(fname, id) {
- var ref = _fnlist[fname].calls[id];
- ref.stop = new Date().getTime();
- ref.total = ref.stop - ref.start;
- }
- /**
- * Add profiling for a given function, identified
- * by the given label. Returns the newly modified
- * function to be assigned to the old function.
- * @example addProfiling('func');
- * @example addProfiling('func', window);
- * @function
- */
- function addProfiling(fname, scope) {
- var scope = scope || window;
- _init(fname, scope[fname], scope);
- var tmpfn = scope[fname];
- scope[fname] = function() {
- var id = _start(fname, tmpfn, arguments);
- var rv = tmpfn.apply(tmpfn, arguments);
- _stop(fname, id);
- return rv; // return result of original function
- }
- }
- /**
- * Remove a function identified by the lable
- * from being profiled. Returns original function
- * to be reassigned.
- * @example removeProfiling('func');
- * @function
- */
- function removeProfiling(fname) {
- _fnlist[fname]['scope'][fname] = _fnlist[fname].fn;
- delete _fnlist[fname];
- }
- /**
- * Report our profiling information via the console.
- * @function
- */
- function profileReport() {
- for (fn in _fnlist) {
- var obj = _fnlist[fn];
- console.log("Function: " + fn + ":");
- console.dir(obj);
- console.log("\tTotal Calls: " + obj['ncalls']);
- var totaltime = 0;
- for (call in obj['calls']) {
- totaltime += obj['calls'][call].total;
- }
- console.log("\tTotal Time (sec): " + (totaltime/1000).toFixed(5));
- }
- }
Add Comment
Please, Sign In to add comment