如何在popen函数C ++中插入一个计时器?

时间:2011-10-29 22:33:18

标签: c++ timer timeout

我有这个功能,输入是var“cmd”,例如dmesg命令。

int i = 0;
char * bufferf;
bufferf = ( char * ) calloc( sizeof ( char ) , 200000 );
char buffer[1000][1280];
memset(buffer,0,1000 * 1280);
memset(bufferf,0,strlen(bufferf));
FILE* pipe = popen(cmd, "r");

if (!pipe){
    send(client_fd,"EXCEPTION",9,0);
}

while(!feof(pipe)) {
    if(fgets(buffer[i], 128, pipe) != NULL)
    {
        strcat(bufferf, buffer [i] );
    }
    i++;
}
pclose(pipe);
std::cout << bufferf ;
send(client_fd,bufferf,strlen(bufferf),0); }

好。我的目标是计算while语句的开始和结束之间的时间量,每次添加一个计算时间的var。

例如dmesg是~700行输出。虽然运行700次,但我必须增加700倍的时间来计算总和。 我怎样才能做到这一点? 我尝试过difftime,但效果不好。 还有其他解决方案吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

你可以创建一个使用clock()来衡量时间的非常基础的课程:

#include <ctime>

class Timer
{
   private:
      clock_t _start, _duration;
   public:
      Timer() : _start(0), _duration(0) { }

      void start() { _start = clock(); }
      void stop() { _duration = clock() - _start; }     
      float getTime() { return (float)_duration / CLOCKS_PER_SEC; }
};

如果你想以毫秒为单位显示时间,显然会乘以1000。

然后只是:

Timer t;
t.start();
// do something
t.stop();

cout << "Duration: " << t.getTime() << endl;

另外,请注意sarnold所说的,buffer是巨大的。