【问题标题】:Performance Issue in Executing Shell Commands执行 Shell 命令时的性能问题
【发布时间】:2013-09-28 08:54:48
【问题描述】:

在我的应用程序中,我需要通过 c++ 代码执行大量的 shell 命令。我发现程序执行6000条命令需要30多秒,这太不可接受了!是否有其他更好的方式来执行 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 秒以下?

【问题讨论】:

  • 你能写一个外部脚本文件然后执行那个文件吗?
  • system(cmd) 呢?
  • @qdii 和 opoen 没有太大区别。

标签: c++ linux performance shell


【解决方案1】:

所以,很可能(根据我在类似事情上的经验),大部分时间都花在启动一个运行 shell 的新进程上,shell 中实际命令的执行时间很短。 (实际上,30 秒内 6000 听起来并不可怕)。

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

另一个想法是,如果您实际上可以将多个字符串组合在一起进行一次执行,也许?

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

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

【讨论】:

  • 我把所有的TC命令组合成一个shell脚本,最后调用system("xxx.sh")来执行这个脚本,却发现它也需要太多时间——最多24秒—— - 虽然少了以前! 24 秒仍然比我们预期的要长得多!
  • 那么您的问题出在 TC 应用程序/命令本身。不确定是否有一个简单的解决方案来解决这个问题......
【解决方案2】:

您可以启动 shell (/bin/sh) 并通过管道将所有命令解析输出。或者您可以创建一个 Makefile,因为这可以让您更好地控制命令的执行方式、并行执行和错误处理。

【讨论】:

    猜你喜欢
    • 2020-10-01
    • 2020-12-12
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2011-06-15
    • 2013-01-05
    • 2010-09-14
    • 2017-04-11
    相关资源
    最近更新 更多