小编Oğu*_*ğlu的帖子

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

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

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 …
Run Code Online (Sandbox Code Playgroud)

c linux pthreads clock

0
推荐指数
1
解决办法
4614
查看次数

标签 统计

c ×1

clock ×1

linux ×1

pthreads ×1