gpt4 book ai didi

android - 使用 gettimeofday 测量执行时间会导致奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:58 25 4
gpt4 key购买 nike

我正在使用 gettimeofday 来测量我用 C++ native 代码为 Android 应用程序编写的函数的执行时间。我创建了一个计时器类来帮助我完成此任务:

timer::timer(){Reset();}

timer::Reset(){
timeval t;
gettimeofday(&t, 0);
start_s = t.tv_sec;
start_ms = t.tv_usec * 0.001f;
}

timer::GetTime(){
timeval t;
gettimeofday(&t, 0);
return (t.tv_sec - start_s)*1000 + t.tv_usec * 0.001f - start_ms;
}

然后,在我的主代码中,我创建两个计时器对象并执行测量,如下所示:

main(){
timer t1, t2;
stringstream str1;
t1.Reset();
for (some count){
t2.Reset();
some_function();
str1 << t2.GetTime() << " ";
}
str1 << t1.GetTime();

output str1;
}

但问题是,当我查看输出结果时,t1 几乎与所有 t2 值相同。如果 for 循环运行五次,输出示例可能为“0.5 0.5 0.4 0.4 0.5 0.55”。

我不明白为什么会发生这种情况。

感谢任何帮助。

谢谢。

最佳答案

我的心灵调试能力告诉我,start_s 和/或 start_ms 在计时器类中被意外声明为静态,并且循环内的每个调用都会从循环外部更新共享的调用。

关于android - 使用 gettimeofday 测量执行时间会导致奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17030694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com