【问题标题】:C++ time function returns same value at different callsC++时间函数在不同的调用中返回相同的值
【发布时间】:2015-05-09 23:38:49
【问题描述】:

我正在尝试使用 C++ 中的时间函数获取网络摄像头的 fps。我正在使用 opencv 库。对于每 100 帧,我计算 fps,所以我确信至少 1-2 秒已经过去。但是,它似乎不起作用,因为 difftime() 返回 0。当我调试代码时,我发现开始时间值和结束时间值是相同的。有人可以帮我解决这个问题吗?以下是我的代码:

int frameCount = 0;
double seconds;
time_t start,end;
double fps;
for(;;){
    start = time(NULL);
    cap >> src;
    if (!src.empty()) {
        frameCount++;
    }
    if(frameCount == 100){
        end = time(NULL);
        seconds = difftime(end, start); //start and end has same value
        fps = frameCount / seconds;
        frameCount = 0;
    }
}

【问题讨论】:

    标签: c++ opencv time


    【解决方案1】:

    您在每次迭代开始时记录start。是否每一百次迭代记录一次end 并不重要,因为start 的值是当前帧中的值。

    start 的初始化移到循环之外,并将其添加到每 100 帧检查的末尾。

    start = time(NULL);
    for(;;){
        cap >> src;
        //...
        if(frameCount == 100){
            end = time(NULL);
            //...
            frameCount = 0;
            start = time(NULL);
        }
    }
    

    【讨论】:

      【解决方案2】:

      为什么将 frameCount 与 100 进行比较?如果您只需要fps,我认为没有充分的理由。

          start = time(NULL); // -> it needs to be initialized outside the loop, otherwise, it will always be equal to end
          for (;;){
      
              cap >> src;
              if (!src.empty()) {
                  frameCount++;
              }
      
              end = time(NULL);
              seconds = difftime(end, start); 
      
              if (seconds != 0)
              { 
                  fps = frameCount / seconds;
                  frameCount = 0;
                  start = time(NULL); // -> reset here the start time
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        • 2020-07-27
        相关资源
        最近更新 更多