Since I'm usually taking a lot more from this group than I'm giving back, I thought I'd offer this up if anyone might find it useful. It's a simple global object for tracking code execution time. (I discovered Firebug's console.time after I'd already written this. Oh well. This one can be used in any browser, anyway.) It has no depedencies on jQuery other than that I happened to use the $ namespace. Feel free to use/extend/modify to your liking.

Usage:

$.timer.start();
// some code
$.timer.mark('optional label');
// some code
$.timer.pause();
// some code to exclude from profiling
$.timer.resume();
// some code
$.timer.mark();
// some code
$.timer.show('optional label'); // displays a list of all marks to this point in an alert pop-up

The code:

// usage: $.debug({x:x, y:y, z:z})
$.debug = function(o) {
    var s = [];
    for (var name in o)
        s.push(name + ': ' + o[name])
    alert(s.join('\n'));
}

$.timer = {
    start: function() {
        this.info = {};
        this.count = 0;
        this.pauseTime = 0;
        this.time = new Date().getTime();
    },
    mark: function(s) {
        var t = ((this.pauseTime == 0) ? new Date().getTime() : this.pauseTime) - this.time;
        this.count++;
        if (s == undefined) s = 'mark ' + this.count;
        this.info[s] = '' + t + ' ms (' + (t/1000) + ' s)';
        this.time = new Date().getTime();
        if (this.pauseTime != 0) this.pauseTime = this.time;
    },
    pause: function() {
        if (this.pauseTime == 0)
            this.pauseTime = new Date().getTime();
    },
    resume: function() {
        if (this.pauseTime != 0)
            this.time += new Date().getTime() - this.pauseTime;
        this.pauseTime = 0;
    },
    show: function(s) {
        this.mark(s);
        $.debug(this.info);
    }
}


Todd

_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/

Reply via email to