为什么在使用基于 clock() 的计时器宏时会得到负值
Why do I get a negative value when using timer MACRO based on clock()?
宏是这样的:
#define MAX 10000000
#define CNT 1000000
#define TIMER_INIT
clock_t starttime, endtime;
#define TIMER(txt, process)
starttime = clock();
process;
endtime = clock();
printf("%-20s %20ldn",
txt, (endtime - starttime))
主要代码是这样的:
char vector2[CNT/8 + 1];
TIMER( "bitsort",
for(i = 0; i < CNT; ++i)
set1(rand() % MAX, vector2));
set1 函数是这样的:
void set1(int pos, char* vector) /* set the position to 1 */
{
vector[pos/8] |= (0x1 << pos%8);
}
当我执行程序时,输出如下所示。
bitsort -36035411302143896
即使我像这样将差异投射到unsigned int
,它仍然不起作用:
#define TIMER(txt, process)
starttime = clock();
process;
endtime = clock();
printf("%-20s %20dn",
txt, (unsigned int)(endtime - starttime))
输出bitsort -16766097
我试图将%ld
修改为%d
,但它不起作用。
但是如果我不在参数中使用for
,如下所示:
TIMER("bitsort", set1(rand() % MAX,vector2));
该TIMER
完美运行,并给了我一个合理的结果。
有人知道我的代码出了什么问题吗?是由宏引起的还是由clock()
函数引起的?谢谢!
我发现了你的问题:
查看此文档 http://www.cplusplus.com/reference/clibrary/cstdio/printf/
注意到 %d 和 %i 的一些内容了吗?有符号十进制整数
您必须使用 %u 或 %lu,因为clock_t是无符号的,而无符号的 int 显然也是无符号的。
编辑:这只是问题的一半,另一半是他在位排序函数中破坏了他的堆栈(MAX 大于 CNT),这要归功于聊天中的@nneonneo找到了这一点。
相关文章:
- Linux的Cpp上的计时器
- 提升 ASIO 无法识别计时器对象
- 提升 asio 并发计时器取消问题与链
- 使用单体计时器的pthread_cond_timedwait有时会比预期晚超时
- 窗口中的微秒计时器
- 计时器是否从另一个线程启动?
- 如何在 c++ 中创建计时器
- C++回调计时器实现
- 在计时器或主线程外部的命令上销毁/替换线程
- 如何制作每秒从 30 乘 1 倒计时的计时器?
- 保留计时器集合(对象与指针)的最佳方法
- 在网络套接字计时器滴答后增加asio短读错误
- 是否可以仅使用标准 c++/c++11 实现不带"sleep"的计时器?
- 在没有NtSetTimerResolution的Windows上提高计时器分辨率(高分辨率)
- 计时器坏了或者其他什么的
- 功能计时器阻止主功能继续
- IO服务重新启动后,Boost最后期限计时器持续触发
- 为什么在使用基于 clock() 的计时器宏时会得到负值
- 计时器精度:c clock( ) vs. WinAPI 的 QPC 或 timeGetTime( )
- 作为计时器,clock()是可靠的吗?