c++ - 使用 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,它实际上甚至不执行子程序,而只是时间命令
解决方案
使用 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);
推荐阅读
- eclipse - 将 Xtext 项目导出到应用程序/可运行
- css - 伪元素在大屏幕和超大屏幕上太小
- python - 如何在漂亮的汤对象中打印两个短语之间的所有行?
- reactjs - 安装 MongoDB 后 Npm React 脚本无法正常工作
- android - 如何指示应用模块覆盖依赖模块中的资源?
- r - 如何从 R 导出多个数据框列表
- oracle - Oracle APEX 更新详细交互式网格中的主列
- laravel - Laravel Mix vue not working and not found css
- c++ - 如何将最新的 Windows SDK 版本传递给 CMake?
- c# - 部分类中的命名空间