首先,我从网上下载了两段程序,不同的写法,同样的功能,我希望知道哪一个运行效率更好一些
function algorithm1();
function algorithm2();
通常我会测试他们运行的时间
var start = new Date;
algorithm1();
var end = new Date;
var interval = end - start;
console.log("Function algorithm1 Finished in " + interval + "ms");
好了,我有了一个运行函数的引擎
function runTest(Fn)
{
var start = new Date;
Fn();
var end = new Date;
var interval = end - start;
console.log("Test Finished in " + interval + "ms");
}
现在我可以知道哪一个算法运行的时间长效率低了
测试的过程中我发现,有一个算法的结果貌似是错误的,我需要判断这个函数的返回值是否正确
另外在函数开始的时候增加了打印信息
我有了第二个版本的引擎:
function runTest(Fn, assertFn, description)
{
console.log("Test Start");
console.log(description);
var start = new Date;
var ret = Fn();
var end = new Date;
var interval = end - start;
assertFn(ret);
console.log("Test Finished in " + interval + "ms");
}
假设我要测试的函数是求n到m的累加和
function sum(n,m)
runTest(function(){return sum(1,10)},
function(ret){if(!ret){console.error("ret should be 55 but got "+ret)}},
"calculate sum(1,10), expect 45");
这样好像太麻烦了,要是能像下面这样就好了
runTest([sum,1,10], assertEqual(45), "calculate sum(1,10)");
根据我们的需要实现assertEqual
function assertEqual(expect)
{
return function(ret){
if(ret != expect)console.error("failed, ret should be " + expect + " but got "+ret);
console.log("Test passed");
}
}
重新实现的runTest
function runTest(FnAndPara, assertFn, description)
{
console.log("Test Start");
console.log(description);
var start = new Date;
var Fn = FnAndPara.shift();
var parameters = FnAndPara;
var ret =Fn.apply(null, parameters);
var end = new Date;
var interval = end - start;
assertFn(ret);
console.log("Test Finished in " + interval + "ms");
}
现在测试之前的算法就容易多了
runTest([algorithm1], assertEqual(100), 'algorithm 1')
runTest([algorithm2], assertEqual(100), 'algorithm 2')
这样在之后的应用中可以进行扩展,比如支持参数的多变,可以只输入函数名,或者增加调用对象,等等
当然这样的框架有很多,写的也非常好,我这里只是一个小学生的作品而已,以学习javascript为目的。