使用clock_gettime(CLOCK_MONOTONIC)测量经过的时间

Oğu*_*ğlu 0 c linux pthreads clock

我必须在多个线程期间消耗测量时间。我必须得到这样的输出:

Starting Time | Thread Number

00000000000   |   1

00000000100   |   2

00000000200   |   3
Run Code Online (Sandbox Code Playgroud)

首先,我使用了 gettimeofday 但我看到有一些负数,然后我做了一些研究并了解到 gettimeofday 无法可靠地测量经过的时间。然后我决定使用clock_gettime(CLOCK_MONOTONIC)。

然而,有一个问题。当我用秒来测量时间时,我无法精确地测量时间。当我使用纳秒时, end.tv_nsec 变量的长度不能超过 9 位数字(因为它是一个长变量)。这意味着,当它必须移动到第 10 位时,它仍然保持在 9 位,并且实际上数字变小,导致经过的时间为负数。

这是我的代码:

long elapsedTime;
struct timespec end;
struct timespec start2;
//gettimeofday(&start2, NULL);
clock_gettime(CLOCK_MONOTONIC,&start2);

while(c <= totalCount)
{   
    if(strcmp(algorithm,"FCFS") == 0)
    {
        printf("In SErunner count=%d \n",count);
        if(count > 0)
        {
            printf("Count = %d \n",count);
        
            it = deQueue();
            c++;
            tid = it->tid;

            clock_gettime(CLOCK_MONOTONIC,&end);
            
            usleep( 1000*(it->value));
            elapsedTime = ( end.tv_sec - start2.tv_sec);
            
            printf("Process of thread %d finished with value %d\n",it->tid,it->value);
            fprintf(outputFile,"%ld %d %d\n",elapsedTime,it->value,it->tid+1);
        }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,timespec 没有微秒变量。如果你能帮助我,我会很高兴。

小智 5

编写一个辅助函数来计算两个时间规范之间的差异:

int64_t difftimespec_ns(const struct timespec after, const struct timespec before)
{
    return ((int64_t)after.tv_sec - (int64_t)before.tv_sec) * (int64_t)1000000000
         + ((int64_t)after.tv_nsec - (int64_t)before.tv_nsec);
}
Run Code Online (Sandbox Code Playgroud)

如果您想要以微秒为单位,只需将其除以 1000,或使用:

int64_t difftimespec_us(const struct timespec after, const struct timespec before)
{
    return ((int64_t)after.tv_sec - (int64_t)before.tv_sec) * (int64_t)1000000
         + ((int64_t)after.tv_nsec - (int64_t)before.tv_nsec) / 1000;
}
Run Code Online (Sandbox Code Playgroud)

请记住包含<inttypes.h>,以便您可以使用转换"%" PRIi64来打印以下int64_t类型的整数:

    printf("%09" PRIi64 " | 5\n", difftimespec_ns(after, before));
Run Code Online (Sandbox Code Playgroud)