为什么在使用基于 clock() 的计时器宏时会得到负值

Why do I get a negative value when using timer MACRO based on clock()?

本文关键字:计时器 clock 为什么      更新时间:2023-10-16

宏是这样的:

#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找到了这一点。