timeval 未返回预期结果
我有一些代码如下所示:
#include <stdio.h>
#include <sys/time.h>
typedef struct{
struct timeval timestamp;
}teststruct;
class TestClass {
public:
TestClass();
void dosomething(int, int);
};
TestClass::TestClass(){
}
void
TestClass::dosomething(int num, int numb) {
}
int main(void){
TestClass *testclass = new TestClass();
teststruct test;
gettimeofday(&test.timestamp, NULL);
printf("%llu \n", test.timestamp.tv_sec);
testclass->dosomething(1,1);
printf("%llu \n", test.timestamp.tv_sec);
}
此代码的输出是:
13825459612132795564 做某事 5598307500
但我不知道为什么第一个数字是混乱的。此外,为了使数字彼此不同,类调用也是完全必要的。
I have some code shown below:
#include <stdio.h>
#include <sys/time.h>
typedef struct{
struct timeval timestamp;
}teststruct;
class TestClass {
public:
TestClass();
void dosomething(int, int);
};
TestClass::TestClass(){
}
void
TestClass::dosomething(int num, int numb) {
}
int main(void){
TestClass *testclass = new TestClass();
teststruct test;
gettimeofday(&test.timestamp, NULL);
printf("%llu \n", test.timestamp.tv_sec);
testclass->dosomething(1,1);
printf("%llu \n", test.timestamp.tv_sec);
}
The output of this code is:
13825459612132795564
dosomething
5598307500
but I have no idea why the first number is messed up. Also the class call is completely necessary in order for the numbers to be different from one another.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我收到警告:格式“%llu”需要类型“long long unsigned int”,但参数 2 的类型为“__time_t”。应该是一个提示。将编译器的警告级别提高到合理的水平。
当您使用正确的输入类型时,它可以工作。否则你会调用 UB,读取不属于你的内存;像这样的错误可能会产生有趣的结果,当你的内存内容发生变化时,这些结果会根据你通常不会期望产生影响的因素而表现出不同的结果。
I get
warning: format ‘%llu’ expects type ‘long long unsigned int’, but argument 2 has type ‘__time_t’
. Should be a hint. Up your compiler's warning level to something sensible.It works when you use the proper input type. You were invoking UB otherwise, reading memory that wasn't yours to read; bugs like this can yield funny results that behave differently based on factors that you wouldn't normally expect to make a difference, as the contents of your memory change.
如果将
%llu
更改为%lu
似乎可以工作。http://codepad.org/YGubabLR
Seems to work if you change the
%llu
to%lu
.http://codepad.org/YGubabLR