Skip to content

Instantly share code, notes, and snippets.

@jeffbonnes
Created September 12, 2011 01:10
Show Gist options
  • Save jeffbonnes/1210394 to your computer and use it in GitHub Desktop.
Save jeffbonnes/1210394 to your computer and use it in GitHub Desktop.
A tracer object to Titanium Mobile to show elapsed time and memory usage
var tracer = {};
(function() {
tracer.levels = {};
tracer.levels.DEBUG = 1;
tracer.levels.INFO = 2;
tracer.levels.WARN = 3;
tracer.levels.ERROR = 4;
tracer.levels.OFF = 5;
tracer.allTracers = [];
tracer.createTracer = function(name) {
var t = {};
t.name = name;
t.startTimer = function(){
t.startTime = (new Date()).valueOf();
};
t.resetMemory = function(){
t.startMem = Ti.Platform.availableMemory;
};
t.startTimer();
t.resetMemory();
function makeMsg( msg ){
var dateTemp = new Date();
var elapsed = dateTemp.valueOf() - t.startTime;
var currMem = Ti.Platform.availableMemory;
var avilableMem = Math.round(currMem) + 'mb';
var deltaMem = Math.round(t.startMem - currMem) + 'mb';
return( t.name + "\t" + elapsed + "\t" + avilableMem + "\t" + deltaMem + "\t" + msg );
};
t.level = tracer.levels.INFO;
t.setLevel = function(level) {
t.level = level;
};
t.debug = function(msg) {
if( t.level <= tracer.levels.DEBUG ){
Ti.API.debug(makeMsg(msg));
}
};
t.info = function(msg) {
if( t.level <= tracer.levels.INFO ){
Ti.API.info(makeMsg(msg));
}
};
t.warn = function(msg) {
if( t.level <= tracer.levels.WARN ){
Ti.API.warn(makeMsg(msg));
}
};
t.error = function(msg) {
if( t.level <= tracer.levels.ERROR ){
Ti.API.error(makeMsg(msg));
}
};
tracer.allTracers.push(t);
return t;
};
tracer.removeTracer = function( t ){
var id = tracer.allTracers.indexOf( t );
if( id > -1 ){
tracer.allTracers.splice( id , 1 );
}
};
tracer.UI = {};
})();
// Example Usage:
var exampleTracer = tracer.createTracer('example');
exampleTracer.setLevel( tracer.levels.INFO );
exampleTracer.debug( "This won't show ");
exampleTracer.info( "This will show");
// Do something that takes long
exampleTracer.startTimer();
for( var i = 0 ; i < 1000000 ; i++ ){
// Do something that takes a while
}
exampleTracer.info( "How long did it take?");
exampleTracer.setLevel( tracer.levels.DEBUG );
exampleTracer.startTimer();
exampleTracer.resetMemory();
var webExample = Ti.UI.createWebView({
url: "http://www.apple.com"
});
webExample.addEventListener('load', function(){
exampleTracer.debug('web view load complete. How much memory did I use?');
});
Ti.UI.currentWindow.add( webExample );
exampleTracer.debug( "done");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment