我有这个简单的函数来计算字母数字。
我的代码是:
function getFreq(str){
var freq={};
str.replace(/[a-z A-Z]/g, function(match){
freq[match] = (freq[match] || 0) + 1;
return match;
});
console.log(JSON.stringify(freq));
return freq;
}
var t0 = performance.now();
function doSomething(s){
getFreq(s);
};
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " ms.")

Enter Here : <input type="text" onchange="doSomething(this.value);" />
&#13;
我想在输入框中输入一些文字后计算getFreq
函数的执行速度。但是这里dosomething
函数在输入框中没有任何数据的情况下运行,即使在键入一些数据后也显示相同的执行时间。
答案 0 :(得分:4)
有api console.time()和console.timeEnd(),你可以使用这个api
了解更多信息 - https://developer.mozilla.org/en-US/docs/Web/API/Console/time
请参阅下面的代码段。
function getFreq(str){
var freq={};
str.replace(/[a-z A-Z]/g, function(match){
freq[match] = (freq[match] || 0) + 1;
return match;
});
console.log(JSON.stringify(freq));
return freq;
}
function doSomething(s){
console.time("getFreq");
getFreq(s);
console.timeEnd("getFreq");
};
&#13;
Enter Here : <input type="text" onchange="doSomething(this.value);" />
&#13;
答案 1 :(得分:1)
t0
,t1
)在方法之外并且从未更改过。将测量值放在方法中。s
是否为空
function getFreq(str){
var freq={};
str.replace(/[a-z A-Z]/g, function(match){
freq[match] = (freq[match] || 0) + 1;
return match;
});
console.log(JSON.stringify(freq));
return freq;
}
function doSomething(s){
if (s === "")
return;
var t0 = performance.now();
getFreq(s);
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " ms.")
};
Enter Here : <input type="text" onchange="doSomething(this.value);" />
答案 2 :(得分:1)
console.time()启动一个名为concatenation的计时器,稍后由console.timeEnd()停止。传递给两个函数调用的计时器名称必须匹配才能使测量工作。
console.time()和console.timeEnd()仅受现代浏览器的支持,从Chrome 2,Firefox 10,Safari 4和Internet Explorer 11开始。
console.time("getFreq");
function getFreq(str){
var freq={};
str.replace(/[a-z A-Z]/g, function(match){
freq[match] = (freq[match] || 0) + 1;
return match;
});
console.log(JSON.stringify(freq));
return freq;
}
console.timeEnd("getFreq");
答案 3 :(得分:1)
这是我想要为每次onChange调用做的事情
function getFreq(str){
var t0 = performance.now();
var freq={};
str.replace(/[a-z A-Z]/g, function(match){
freq[match] = (freq[match] || 0) + 1;
return match;
});
console.log(JSON.stringify(freq));
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " ms.")
return freq;
}
<input type="text" onchange="getFreq(this.value);" />
输出:
{"a":1,"b":1,"c":3," ":2,"A":1,"D":1}
Call to doSomething took 1.4000000000014552 ms.
{"a":1,"b":1,"c":4," ":3,"A":2,"D":1}
Call to doSomething took 1.9250000000029104 ms.