Mail Archives: djgpp/2001/12/06/11:19:40
On 6 Dec 2001 at 10:34, Marp wrote:
> I think I might have run into an optimizer bug in GCC 3.0.2, but I need some
> insight. I have the version dated Nov 21, 2001 on the ftp server.
>
> Consider the following program:
>
> #include <stdio.h>
> #include <dos.h>
>
> int main(void) {
> union {
> unsigned long long full;
> struct {
> unsigned long lo, hi;
> } half;
> } before, after;
>
> asm("rdtsc" : "=a" (before.half.lo), "=d" (before.half.hi));
> delay(1000); // pause for 1 second
> asm("rdtsc" : "=a" (after.half.lo), "=d" (after.half.hi));
>
> printf("CPU Speed: %llu MHz\n", (after.full - before.full) / 1000000llu);
>
> return 0;
> }
>
> If I compile with no optimization (gcc foo.c -o foo.exe -s) the program
> outputs the correct result (400). However, if I turn on the optimizer (gcc
> foo.c -o foo.exe -s -O1) the program outputs an incorrect result (0). When I
> inspect the assembly output of the compiler, the one difference that caught
> my attention is that the second asm statement appears to be missing when the
> optimizer is turned on. Now I'm not exactly an expert with assembly, but I
> don't see how a correct result could be computed without that second asm
> statement.
>
> So can someone explain to me what is wrong? Is it a gcc bug, or my mistake?
GCC tries to be too wise and optimizes one rdtsc out. Use
'asm volatile ("rdtsc" : ... )' to force it not do wrong optimization.
Anyway I would suggest a different aproach fo measuring clock frequency
like reading rdtsc from timer interrupt procedure (or RTC interrupt procedure),
using delay together with uclock() or something similar.
Andris
- Raw text -