我试图使用时间()来测量我的程序的各个点。

我不明白的是为什么前后的值是一样的?我知道这不是分析我的程序的最佳方式,我只是想看看需要多长时间。

printf("**MyProgram::before time= %ld\n", time(NULL));

doSomthing();
doSomthingLong();

printf("**MyProgram::after time= %ld\n", time(NULL));

我试过:

struct timeval diff, startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

timersub(&endTV, &startTV, &diff);

printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);

我如何读取**时间花费= 0 26339的结果?这是否意味着26339纳秒= 26.3毫秒?

**时间= 4 45025,这是否意味着4秒25毫秒?


当前回答

在linux上,clock_gettime()是一个很好的选择。 必须链接实时库(-lrt)。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define BILLION  1000000000L;

int main( int argc, char **argv )
  {
    struct timespec start, stop;
    double accum;

    if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    system( argv[1] );

    if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    accum = ( stop.tv_sec - start.tv_sec )
          + ( stop.tv_nsec - start.tv_nsec )
            / BILLION;
    printf( "%lf\n", accum );
    return( EXIT_SUCCESS );
  }

其他回答

//***C++11 Style:***
#include <chrono>

std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[µs]" << std::endl;
std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << "[ns]" << std::endl;

从所看到的内容来看,tv_sec存储所经过的秒数,而tv_usec单独存储所经过的微秒数。它们不是彼此的转换。因此,必须将它们更改为适当的单位,并添加它们以获得所消耗的总时间。

struct timeval startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

printf("**time taken in microseconds = %ld\n",
    (endTV.tv_sec * 1e6 + endTV.tv_usec - (startTV.tv_sec * 1e6 + startTV.tv_usec))
    );

我需要测量库中各个函数的执行时间。我不希望每个函数的每次调用都用一个时间度量函数来包装,因为这样做很难看,而且会加深调用堆栈。我也不想把定时器代码放在每个函数的顶部和底部,因为当函数可能提前退出或抛出异常时,这会造成混乱。所以我最终做了一个计时器,用它自己的生命周期来测量时间。

通过这种方式,我可以测量一个代码块的wallall时间,方法是在有问题的代码块(函数或任何作用域)的开头实例化这些对象之一,然后允许实例析构函数测量实例超出作用域时自构造以来所花费的时间。你可以在这里找到完整的例子,但结构体非常简单:

template <typename clock_t = std::chrono::steady_clock>
struct scoped_timer {
  using duration_t = typename clock_t::duration;
  const std::function<void(const duration_t&)> callback;
  const std::chrono::time_point<clock_t> start;

  scoped_timer(const std::function<void(const duration_t&)>& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  scoped_timer(std::function<void(const duration_t&)>&& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  ~scoped_timer() { callback(clock_t::now() - start); }
};

当函数超出作用域时,该结构体将回调所提供的函数,这样您就可以对计时信息做一些事情(打印它或存储它或其他什么)。如果你需要做一些更复杂的事情,你甚至可以使用std::bind和std::占位符来回调函数。

下面是一个快速使用它的例子:

void test(bool should_throw) {
  scoped_timer<> t([](const scoped_timer<>::duration_t& elapsed) {
    auto e = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(elapsed).count();
    std::cout << "took " << e << "ms" << std::endl;
  });

  std::this_thread::sleep_for(std::chrono::seconds(1));

  if (should_throw)
    throw nullptr;

  std::this_thread::sleep_for(std::chrono::seconds(1));
}

如果您希望更加谨慎,还可以使用new和delete显式地启动和停止计时器,而不依赖于作用域。

这两个值相同的原因是因为您的长过程不需要那么长时间—不到一秒。你可以试着添加一个长循环(for (int i = 0;I < 100000000;i++);)在函数的末尾确保这是问题所在,然后我们可以从那里…

如果上面的情况是正确的,你将需要找到一个不同的系统函数(我知道你在linux上工作,所以我不能帮助你知道函数名称)来更准确地测量时间。我相信在linux中有一个类似于GetTickCount()的函数,你只需要找到它。

回答OP的三个具体问题。

“我不明白的是,为什么之前和之后的数值是一样的?”

第一个问题和示例代码显示time()的分辨率为1秒,因此答案必须是两个函数在1秒内执行。但如果两个计时器标记跨越了一秒的边界,它偶尔会(显然是不合逻辑的)通知1秒。

下一个示例使用gettimeofday()填充该结构体

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

第二个问题是:“我如何读取**时间= 0 26339的结果?这是否意味着26339纳秒= 26.3毫秒?”

我的第二个答案是所花费的时间是0秒和26339微秒,即0.026339秒,这证实了第一个示例在不到1秒的时间内执行。

第三个问题是:“**时间= 4 45025,这是否意味着4秒25毫秒?”

我的第三个答案是所用的时间是4秒和45025微秒,即4.045025秒,这表明OP改变了他之前计时的两个函数执行的任务。