今天我尝试为 javascript 函数编写一个简单的 prophiler 实用程序。问题是我启动的交互越多,系统速度就越慢,所以我认为在某些时候我有内存泄漏导致这个问题。实验代码如下。
//Benchmark prototype
var Prophiler = (function( ){
var _benchMark = (function( func, duration, callBack ){
var _interval = 1000;
var _startMark = new Date().getTime();
var _now = _startMark;
var _count = 0;
var _rounds = 0;
var _throttle = (function( ){
while( ( _now - _startMark ) < _interval ){
func( );
_now = new Date().getTime( );
_count++;
}
_startMark = new Date().getTime();
_rounds++;
if( _rounds <= ( duration ) ){
window.setTimeout( _throttle, 25 );
return false;
}
else{
var _res = {};
_res.elapsedTime = duration;
_res.executions = _count;
_res.averageTime = _res.elapsedTime / _res.executions;
_res.averageTimeMs = _res.averageTime * 1000;
callBack( _res );
return false;
}
});
_throttle( );
});
return{
getProphile : function( params ){
_benchMark( params.subject, params.duration, params.callBack );
}
}
})( );
//Test
var sumNum = function( param1, param2 ){
var y = param1;
for( var i = 0; i < param2; i++ ){
y += param2;
}
};
Prophiler.getProphile({
subject: function( ){
sumNum( 10, 30 );
},
duration: 5,
callBack: function( data ){
console.log( data );
}
});