业务需求是:我们产品功能有一个需要通过本机IP去ping空闲IP 然后拿一个空闲IP默认给用户展示
const GetIdleIP = (ips: string, platform: string) => {
let ip = ips.substring(0, ips.lastIndexOf("."));
return new Promise((resolve, reject) => {
const wreg = /\d+ms\sTTL\=/;
const lreg = /icmp_seq=\d+ ttl=+/;
const ips = [] as any;
const promises = [];
for (let i = 1; i <= 254; i++) {
promises[i] = new Promise(r => {
if (platform == "win32" || platform == "darwin") {
sudo(`ping ${ip}.${i} -4 -n 1`, (err: any, stdout: string, stderr: string) => {
const rs = stdout.split("\n").slice(2, 5);
const flag = rs.some(str => wreg.test(str));
if (!flag) {
ips.push(`${ip}.${i}`);
}
r("1");
});
} else {
sudo(`ping ${ip}.${i} -c 1`, (err: any, stdout: string, stderr: string) => {
const rs = stdout.split("\n").slice(2, 5);
const flag = rs.some(str => lreg.test(str));
if (!flag) {
ips.push(`${ip}.${i}`);
}
r("1");
});
}
});
}
Promise.all(promises).then(res => {
if (res.length > 0) {
resolve(ips);
}
})
}).then().catch();
}
这是通过创建promise创建任务去pingIP 而最早完成的时候只花了3秒就完成了。而最近测试却发现足足花了25秒才会返回结果!!终究是什么地方出现了问题呢,跟我的好兄弟最早一起研究,甚至更改写法 用了worker 多线程等等尝试 发现时间依然没有改变多少,最后写了个demo测试 在我好兄弟电脑仅仅只花了3秒 而我花了25秒
const process = require("child_process");
new Promise((resolve, reject) => {
const exec = process.exec;
const reg = /\d+ms\sTTL\=/;
const ips = [];
const promises = [];
console.time(1)
for (let i = 0; i <= 255; i++) {
promises[i] = new Promise(resolve => {
console.timeLog(1, `${i}进入Promise`)
exec(`ping 192.168.1.${i} -4 -n 1`, (err, stdout, stderr) => {
console.timeLog(1, `${i}完成`)
const rs = stdout.split("\n").slice(2, 5);
const flag = rs.some(str => reg.test(str));
if (!flag) {
ips.push(`192.168.1.${i}`);
}
resolve();
});
});
}
Promise.all(promises).then(res => {
if (res.length == 256) {
console.timeEnd(1);
console.log(ips);
}
})
});
甚至更换过node 也拿过同事同配置电脑测试过
经过很多次不同电脑尝试最后得出原因 与node 电脑配置关系并没有那么大。而是电脑开了360......
把360关了最慢跑完还是会在3-5秒左右