Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: question about optimizing code

Author: Russell Reagan

Date: 14:40:46 07/07/03

Go up one level in this thread


This implements Tim's method. I get the output n = 1799993753, time = 6.339 on
Athlon 2GHz. Let's implement some of the others and compare.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_ITERATIONS 10000000

unsigned long n = 0;

int smallestpower[256] = {
-1, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
};

// Just some functions to call
void func0 () { n += 1; }
void func1 () { n += 2; }
void func2 () { n += 3; }
void func3 () { n += 4; }
void func4 () { n += 5; }
void func5 () { n += 6; }
void func6 () { n += 7; }
void func7 () { n += 8; }

void tim_func () {
    int i;
    clock_t start, stop;

    srand(0);
    start = clock();
    for (i = 0, n = 0; i < MAX_ITERATIONS; i++) {
        unsigned long bits = rand() & 0xff;
        while (bits) {
            int bit = smallestpower[bits];
            switch (bit) {
                case 0: func0(); break;
                case 1: func1(); break;
                case 2: func2(); break;
                case 3: func3(); break;
                case 4: func4(); break;
                case 5: func5(); break;
                case 6: func6(); break;
                case 7: func7(); break;
            }
            bits ^= (1 << bit);
        }
    }
    stop = clock();
    printf("n = %u, time = %.3f\n", n, (float)(stop - start) / CLOCKS_PER_SEC);
}

void main (void) {
    tim_func();
}



This page took 0.01 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.