我必须跟踪任务执行了多长时间。我在 Linux 上工作,但我无权访问内核本身。
我的任务只是忙循环,直到进程已经执行了一定时间。那么这个过程应该会跳出这个循环。
我有一个使用 time.h
中的 clock_gettime()
的工作版本。在我忙于循环“开始”变量之前,我存储了自 Epoch 以来的时间。然后在循环的每次迭代中,我再次在另一个名为“current”的变量中检查自 Epoch 以来的时间。
哦,循环的每次迭代,我都区分了“current”和“start”。如果该差异大于或等于我请求的执行时间,我就会跳出循环。
问题是 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;
}
}
最佳答案
将 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);
}
关于c - 在 C 中跟踪任务的执行时间(忽略时间任务被挂起),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787020/