我尝试计算通过循环的操作次数为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
都会变成相同的值!虽然t
和tstep
不同!
看起来这是因为引用:可能当我使用tstep = t
时,这意味着此变量的地址都指向t
。因此,更改t
更改now
和tstep
。
如何解决这个问题?如何仅将t
的值复制到step
?还是有另一种实际的方式?
答案 0 :(得分:6)
localtime
函数不是线程安全的,更重要的是不可重入。
它返回的指针很可能是指向内部static
缓冲区的指针。这意味着每个localtime
调用返回的指针都指向同一个&#34;缓冲区&#34; (结构体)。实际上,如果您读取链接引用,则缓冲区(结构)可以在多个函数之间共享。
可以使用调试器轻松检查,并比较函数返回的指针。
如果需要不同的值,则需要复制数据而不是复制指针。这可以通过使now
和step
结构实例而不是指针来完成。然后取消引用localtime
返回的指针:
struct tm now, step; // Note: Not pointers!
...
now = *localtime(&t); // Dereference returned pointer