我必须跟踪任务执行的时间。我正在Linux上工作,但是无法访问内核本身。
我的任务只是忙循环,直到该进程执行了一定时间。然后,该过程应打破此循环。
我有一个使用clock_gettime()
中的time.h
的版本。在我忙于循环输入“ start”变量之前,我存储了从Epoch开始的时间。然后,在循环的每次迭代中,我都在另一个称为“当前”的变量中检查了自大纪元以来的时间。
哦,循环的每次迭代,我都采用了“当前”和“开始”之间的区别。如果该差异大于或等于我请求的执行时间,我就会跳出循环。
麻烦在于clock_gettime()
并未将任务暂停。因此,如果我的任务挂起,则我现在执行此操作的方式将把任务挂起的时间视为仍在执行。
有人clock_gettime()
的替代者允许计时器以某种方式忽略暂停时间吗?我当前方法的代码如下。
//DOES NOT HANDLE TASK SUSPENSION
#include <time.h>
#define BILLION 1E9
//Set execution time to 2 seconds
double executionTime = 2;
//Variable used later to compute difference in time
double elapsedTime = -1;
struct timespec start;
struct timespec current;
//Get time before we busy-loop
clock_gettime(CLOCK_REALTIME, &start);
int i;
for (i = 0; i < 10000000000; i++)
{
//Get time on each busy-loop iteration
clock_gettime(CLOCK_REALTIME, ¤t);
elapsedTime = (current.tv_sec - start.tv_sec) + ((current.tv_nsec - start.tv_nsec) / BILLION);
//If we have been executing for the specified execution time, break.
if (elapsedTime >= executionTime)
{
break;
}
}
答案 0 :(得分:1)
将CLOCK_REALTIME
更改为CLOCK_PROCESS_CPU_TIME
。
使用sleep()
会花费几秒钟来累积少量的CPU时间。
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#define BILLION 1E9
int main ( void) {
double executionTime = 0.0001;
double elapsedTime = -1;
double elapsedTimertc = -1;
struct timespec startrtc;
struct timespec start;
struct timespec currentrtc;
struct timespec current;
clock_gettime(CLOCK_REALTIME, &startrtc);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
for (;;)
{
sleep ( 1);
clock_gettime(CLOCK_REALTIME, ¤trtc);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ¤t);
elapsedTime = (current.tv_sec - start.tv_sec) + ((current.tv_nsec - start.tv_nsec) / BILLION);
elapsedTimertc = (currentrtc.tv_sec - startrtc.tv_sec) + ((currentrtc.tv_nsec - startrtc.tv_nsec) / BILLION);
if (elapsedTime >= executionTime)
{
break;
}
}
printf ( "elapsed time %f\n", elapsedTime);
printf ( "elapsed time %f\n", elapsedTimertc);
}