首页 > 解决方案 > 使用 popen 定时运行程序

问题描述

我是 C++ 的新手,我正在尝试构建一个运行带有 popen 的命令的程序,并获取 popen()ed 命令的执行时间。

我已经尝试过使用clock() 函数,但它只会得到popen() 分叉和管道的时间,而不是实际的子命令执行时间。

所以问题是:有没有办法检查 popen()ed 命令的执行时间?

string command = "some time consuming command";
FILE *process; 
char buff[1024];

char cCommand[command.size() + 1];
strcpy(cCommand, command.c_str());

fflush(NULL);
process = popen(cCommand, "r");

if (process != NULL) {
    while (!feof(process)) {
        
        fgets(buff, sizeof(buff), process);
        // Doing something with my output
    }
    
    r = pclose(process);
}
return WEXITSTATUS(r);

编辑:我也忘了提到我尝试使用 unix/bin/bash -c time <subprogram path>但每次它返回时间 0,它实际上甚至不执行子程序,而只是时间命令

标签: c++

解决方案


使用 std::chrono


string command = "some time consuming command";
FILE *process; 
char buff[1024];

char cCommand[command.size() + 1];
strcpy(cCommand, command.c_str());

fflush(NULL);
// Gets the now() time before the command is launched
auto start = std::chrono::system_clock::now();
process = popen(cCommand, "r");

if (process != NULL) {
    while (!feof(process)) {

        fgets(buff, sizeof(buff), process);
        // Doing something with my output 
    }

    r = pclose(process);
    // Gets the now time after the command has terminated
    auto end = std::chrono::system_clock::now();
    // Finish - start = elapsed time
    std::chrono::duration<double> elapsed_seconds = end - start;
    time = elapsed_seconds.count();
}

return WEXITSTATUS(r);


推荐阅读