0

我有一个关于在 Ubuntu 12.04 上测量 CPU 时间的问题。

我想在某个循环中使用 CPU 时间作为停止标准。什么是最好的方法?

while(....)
{
    //main part
    // get CPUTIME
    if(CPUTIME>= Given_Time)
    {
        break;         
    }

}

1)clock()如果我不太关心时间的分辨率,我可以使用。

time_t begin=clock();
....
time_t end=clock();

CPUTIME=(double)(end-begin)/(double)(CLOCKS_PER_SEC);

然而,time_t许多是溢出的,因为运行时间可能很长(超过一个小时)。我该如何解决这个问题?

2)第二个选项是使用getrusage(int who, struct rusage *usage) 在循环中调用这个函数是否花费太多?

3)第三个选项是使用int clock_gettime(clockid_t clk_id, struct timespect *tp) 到目前为止,这是我的选项中最好的选择。

任何建议和意见都会有所帮助。

4

1 回答 1

1

Depending on how fast your loop is running, you might not want to call the checking function every cycle. Perhaps add a loop counter and check the CPU time only if, for example, (i % 1000) == 0.

To answer your question: I'd personally use clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) because librt, the library in which this function resides, was made specifically for tasks like this. However, there's no reason that you can't use the other two; you can easily detect the overflow with clock() by detecting when the value wraps and having a separate counter that counts the number of times it wraps.

于 2012-06-16T04:50:23.563 回答