gpt4 book ai didi

c++ - 执行 Shell 命令时的性能问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:13 24 4
gpt4 key购买 nike

在我的应用程序中,我需要通过 C++ 代码执行大量的 shell 命令。我发现程序执行6000条命令需要30多秒,这太 Not Acceptable 了!有没有其他更好的方法来执行 shell 命令(使用 c/c++ 代码)?

    //Below functions is used to set rules for 
//Linux tool --TC, and in runtime there will
//be more than 6000 rules to be set from shell
//those TC commans are like below example:

//tc qdisc del dev eth0 root
//tc qdisc add dev eth0 root handle 1:0 cbq bandwidth
// 10Mbit avpkt 1000 cell 8
//tc class add dev eth0 parent 1:0 classid 1:1 cbq bandwidth
// 100Mbit rate 8000kbit weight 800kbit prio 5 allot 1514
// cell 8 maxburst 20 avpkt 1000 bounded
//tc class add dev eth0 parent 1:0 classid 1:2 cbq bandwidth
// 100Mbit rate 800kbit weight 80kbit prio 5 allot 1514 cell
// 8 maxburst 20 avpkt 1000 bounded
//tc class add dev eth0 parent 1:0 classid 1:3 cbq bandwidth
// 100Mbit rate 800kbit weight 80kbit prio 5 allot 1514 cell
// 8 maxburst 20 avpkt 1000 bounded
//tc class add dev eth0 parent 1:1 classid 1:1001 cbq bandwidth
// 100Mbit rate 8000kbit weight 800kbit prio 8 allot 1514 cell
// 8 maxburst 20 avpkt 1000
//......

void CTCProxy::ApplyTCCommands(){
FILE* OutputStream = NULL;

//mTCCommands is a vector<string>
//every string in it is a TC rule
int CmdCount = mTCCommands.size();
for (int i = 0; i < CmdCount; i++){
OutputStream = popen(mTCCommands[i].c_str(), "r");
if (OutputStream){
pclose(OutputStream);
} else {
printf("popen error!\n");
}
}
}

更新
我尝试将所有 shell 命令放入一个 shell 脚本中,让测试应用程序使用 system("xxx.sh") 调用这个脚本文件。这次执行所有 6000 条 shell 命令需要 24 秒,比我们之前计算的要少。但这仍然比我们预期的要大得多!有没有其他方法可以将执行时间减少到 10 秒以内?

最佳答案

因此,很可能(根据我在类似类型事物中的经验),大部分时间花在启动一个运行 shell 的新进程上,在 shell 中执行实际命令的时间非常短。 (实际上,30 秒内达到 6000 次听起来并不算太糟糕)。

有多种方法可以做到这一点。我很想尝试将它们全部组合到一个 shell 脚本中,而不是运行单独的行。这将涉及将所有“tc”字符串写入一个文件,然后将其传递给 popen()。

另一个想法是,如果您真的可以将多个字符串组合到一个执行中,也许吧?

如果命令完整且可直接执行(即不需要 shell 来执行程序),您也可以自己执行 forkexec。这将节省创建一个 shell 进程,然后创建实际进程。

此外,您可以考虑并行运行少量进程,这在任何现代机器上都可能会根据您拥有的处理器内核数量来加快速度。

关于c++ - 执行 Shell 命令时的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19065156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com