The macro is like this:
#define MAX 10000000
#define CNT 1000000
#define TIMER_INIT \
clock_t starttime, endtime; \
#define TIMER(txt, process) \
starttime = clock(); \
process; \
endtime = clock(); \
printf("%-20s %20ld\n", \
txt, (endtime - starttime))
The main codes is like this:
char vector2[CNT/8 + 1];
TIMER( "bitsort",
for(i = 0; i < CNT; ++i)
set1(rand() % MAX, vector2));
And the set1 function is like this:
void set1(int pos, char* vector) /* set the position to 1 */
{
vector[pos/8] |= (0x1 << pos%8);
}
When I execute the program, the output looks like this..
bitsort -36035411302143896
Even if I cast the difference to unsigned int like this, it still doesn’t work:
#define TIMER(txt, process) \
starttime = clock(); \
process; \
endtime = clock(); \
printf("%-20s %20d\n", \
txt, (unsigned int)(endtime - starttime))
Output is bitsort -16766097
I tried to modify %ld to %d, but it doesn’t work.
But if I don’t use for in the parameter, like this:
TIMER("bitsort", set1(rand() % MAX,vector2));
The TIMER works perfectly and gives me a reasonable result..
Does anyone have idea about what’s wrong with my code? Is it caused by macro or by clock() function? Thanks!
I have found your issue:
Look at this documentation http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Notice something about %d and %i? Signed decimal integer
You must use %u or %lu because clock_t is unsigned, and an unsigned int is also obviously unsigned.
Edit: This was only half of the problem, the other half was that he was destroying his stack(MAX is larger than CNT) in the bitsort function, thanks to @nneonneo in the chat for finding that.