Created
December 12, 2014 18:14
-
-
Save joelandman/ec6f3abef9bc5f1c7b0e to your computer and use it in GitHub Desktop.
Quick and dirty log_2 tester ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <math.h> | |
#include <sys/time.h> | |
#define NUMBER_OF_CALIPER_POINTS 10 | |
struct timeval ti,tf,caliper[NUMBER_OF_CALIPER_POINTS]; | |
struct timezone tzi,tzf; | |
int log_2 (unsigned int v) | |
{ | |
register unsigned int r; // result of log2(v) will go here | |
register unsigned int shift; | |
r = (v > 0xFFFF) << 4; v >>= r; | |
shift = (v > 0xFF ) << 3; v >>= shift; r |= shift; | |
shift = (v > 0xF ) << 2; v >>= shift; r |= shift; | |
shift = (v > 0x3 ) << 1; v >>= shift; r |= shift; | |
r |= (v >> 1); | |
return r; | |
} | |
int main (int argc, char **argv) | |
{ | |
int i, x, milestone; | |
float logx; | |
int sx = 0 , sumlogx = 0 ; | |
double delta_t; | |
milestone = 0; | |
gettimeofday(&caliper[milestone],&tzf); | |
for(x=1; x<65536; x++) sx+=(int)log2((double)x); | |
milestone++; | |
gettimeofday(&caliper[milestone],&tzf); | |
for(x=1; x<65536; x++) sumlogx+=log_2((unsigned int)x); | |
milestone++; | |
gettimeofday(&caliper[milestone],&tzf); | |
printf("library function sum: %i\n",sx); | |
printf("local function sum: %i\n",sumlogx); | |
/* now report the milestone time differences */ | |
for (i=0;i<=(milestone-1);i++) | |
{ | |
delta_t = (double)(caliper[i+1].tv_sec-caliper[i].tv_sec); | |
delta_t += (double)(caliper[i+1].tv_usec-caliper[i].tv_usec)/1000000.0; | |
printf("milestone=%i to %i: time = %.5f seconds\n",i,i+1,delta_t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And if we change the log_2 function to
int log_2 (unsigned int v)
{
int r; // result goes here
}
The timing gets even better:
landman@metal:~/work/development/log$ gcc -o log2a.x log2a.c -lm ; ./log2a.x
library function sum: 917506
local function sum: 917506
milestone=0 to 1: time = 0.00284 seconds
milestone=1 to 2: time = 0.00065 seconds
Almost 5x at the same level of precision.