Skip to content

C64: Optimize ilog2 using bit twiddling hack#6

Open
visitorckw wants to merge 1 commit into
onnokort:masterfrom
visitorckw:optimize/ilog2-bit-twiddling
Open

C64: Optimize ilog2 using bit twiddling hack#6
visitorckw wants to merge 1 commit into
onnokort:masterfrom
visitorckw:optimize/ilog2-bit-twiddling

Conversation

@visitorckw

Copy link
Copy Markdown

I conducted a micro-benchmark[1] testing the efficiency of inputs ranging from 1 to 10,000,000, and observed a significant improvement, validating the effectiveness of the implemented optimization. Additionally, I validated the correctness of the optimization by running a unit test[2] loop over all values from 1 to 0xffffffff as input and comparing the results with the expression 31 - __builtin_clz(x | 1). The comprehensive test ensures the accuracy of the implemented optimization.

[1]:

/*
 * Benchmark the performance of ilog2 and ilog2_old.
 * Time of new ilog2: 71
 * Time of old ilog2: 359
*/
void benchmark()
{
    const int loop = 10000000;
    long long int t_old, t_new;

    t_new = clock();
    for(uint32_t i = 1; i < loop; i++) {
        int y = ilog2(i);
    }
    t_new = clock() - t_new;

    t_old = clock();
    for(uint32_t i = 1; i < loop; i++) {
        int y = ilog2_old(i);
    }
    t_old = clock() - t_old;

    printf("Time of new ilog2: %lld\n", t_new);
    printf("Time of old ilog2: %lld\n", t_old);
}

[2]:

/* Return 0 on success and return 1 on failure. */
int unit_test()
{
    uint32_t x = 1;
    while(1) {
        int y = ilog2(x);
        int z = 31 - __builtin_clz(x | 1);
        if(y != z) return 1;
        if(x == 0xffffffff) break;
        x++;
    }
    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant