Skip to content

Instantly share code, notes, and snippets.

@eienf
Last active December 17, 2015 05:48
Show Gist options
  • Save eienf/5559999 to your computer and use it in GitHub Desktop.
Save eienf/5559999 to your computer and use it in GitHub Desktop.
Time mesurement for decimal to binary change function.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <mach/mach_time.h>
#define DEBUG 0
int digit3(unsigned long n)
{
if ( n == 0 ) return 1;
int max = sizeof(unsigned long)*8;
for ( int i = 0; i < max; i++, n>>=1 ) {
if (n==0) {
return i;
}
}
return 1;
}
int digit2(unsigned long n)
{
if ( n == 0 ) return 1;
int max = sizeof(unsigned long)*8;
unsigned long mask = (unsigned long)1<<(max-1);
#if DEBUG
printf("%d %lx %lx\n",max,mask,n);
#endif
for ( int i = max; i > 0; i--,mask>>=1 ) {
if (n&mask) {
return i;
}
}
return 1;
}
int digit(unsigned long n)
{
if ( n == 0 ) return 1;
int k = (int)(log2(n));
return k+1;
}
char *binary(long decimal,char *buff,int length)
{
int d = digit(decimal);
#if DEBUG
printf("digit = %d\n",d);
#endif
if ( buff == NULL || length == 0 ) {
buff = malloc(d+1);
}
buff[d] = 0;
for ( int i = 0; i < d; i++ ) {
if ( ( decimal >> (d-i-1) ) % 2 ) {
buff[i] = '1';
} else {
buff[i] = '0';
}
}
#if DEBUG
printf("decimal = %ld\n",decimal);
printf("binary = %s\n",buff);
#endif
return buff;
}
int main(int argc,char *argv[])
{
if ( argc < 2 ) {
fprintf(stderr,"Usage : %s repeat_count\n",argv[0]);
return -1;
}
srandom((unsigned int)time(NULL));
int count = atoi(argv[1]);
char result[sizeof(long)*8+1];
uint64_t start, elapsed;
mach_timebase_info_data_t base;
mach_timebase_info(&base);
start = mach_absolute_time();
for ( int i = 0; i < count; i++ ) {
long decimal = (long)random();
#if DEBUG
decimal &= 0x0ffff;
#endif
binary(decimal,result,sizeof(result));
}
elapsed = mach_absolute_time() - start;
uint64_t nsec = elapsed * base.numer / base.denom;
printf("time = %lld(nsec) : count = %d\n",nsec,count);
printf("time = %lld(nsec)\n",nsec/count);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment