引用C ++

时间:2017-08-16 08:42:25

标签: c++ visual-studio loops time reference

我尝试计算通过循环的操作次数为1秒。 为此,我记得我开始计算循环并在每次迭代时检查时间的时间。 我的想法 - 当这两个时间段的秒数不同时,我打印了多少循环迭代。

这是我的代码:

#include <ctime>
int main()
{
    // For timing
     time_t t, tstep;
     struct tm* now, *step;

    // this time will change at every iteration
    t = time(0);
    now = localtime(&t);

    // save time of the start moment
    tstep = t;
    step = localtime(&tstep);

    // counter of loop cycles
    int count = 0; 

    for (size_t i = 0; i < 1e100 ; i++)
    {
        // ... here is some calculations    
        t = time(0);
        now = localtime(&t);
        count++;

        if (now->tm_sec != step->tm_sec)
        {
            tstep = time(0);
            step = localtime(&tstep);
             //printf("number of lines %i \n", count );
             count = 0;
        }
    }
    return 0;
}

问题是什么:每次刷新now step都会变成相同的值!虽然ttstep不同!

看起来这是因为引用:可能当我使用tstep = t时,这意味着此变量的地址都指向t。因此,更改t更改nowtstep

如何解决这个问题?如何仅将t的值复制到step?还是有另一种实际的方式?

1 个答案:

答案 0 :(得分:6)

localtime函数不是线程安全的,更重要的是不可重入。

它返回的指针很可能是指向内部static缓冲区的指针。这意味着每个localtime调用返回的指针都指向同一个&#34;缓冲区&#34; (结构体)。实际上,如果您读取链接引用,则缓冲区(结构)可以在多个函数之间共享。

可以使用调试器轻松检查,并比较函数返回的指针。

如果需要不同的值,则需要复制数据而不是复制指针。这可以通过使nowstep结构实例而不是指针来完成。然后取消引用localtime返回的指针:

struct tm now, step;  // Note: Not pointers!

...

now = *localtime(&t);  // Dereference returned pointer