Skip to content

Instantly share code, notes, and snippets.

@radbasa
Created May 30, 2014 14:53
Show Gist options
  • Save radbasa/8002a4705d47ae147e26 to your computer and use it in GitHub Desktop.
Save radbasa/8002a4705d47ae147e26 to your computer and use it in GitHub Desktop.
3 way comparison
//
// main.c
// optimize
//
// Created by Rodrigo Basa on 2014-05-29.
// Copyright (c) 2014 Rodrigo Basa. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
double time_diff(struct timeval x , struct timeval y);
int main(int argc, const char * argv[]) {
const int samples = 1000000;
struct timeval start , end;
double lessifs = 0;
double orig = 0;
double moreifs = 0;
int w, x, f;
char z;
srand( (unsigned) time( NULL ) );
for ( int i = 0; i < samples; i++ ) {
// Common set of data
w = rand() % 2; // 0 or 1
x = rand() % 80; // 0 to 80
f = rand() % 2; // 0 or 1 converted to 'F' and 'M' below
if ( f == 1 )
z = 'M';
else
z = 'F';
//Original
gettimeofday(&start, NULL);
if ( w == 1 ) {
if ( z == 'M' ) {
if ( x >= 20 && x <= 65 ) {
// statements 1
} else if ( x < 20 ) {
// statements 3
}
} else {
if ( x >= 20 ) {
if ( x <= 65 ) {
// statements 1
// statements 2
} else {
// statements 2
}
}
}
} else {
if ( z == 'M' ) {
if ( x < 20 ) {
// statements 3
}
} else {
if ( x >= 20 ) {
// statements 2
}
}
}
gettimeofday(&end, NULL );
orig += time_diff( start, end );
// Less ifs, no nesting
// measure only the time spent in the conditional blocks
gettimeofday(&start , NULL);
if ( (w == 1) && (x >= 20) && (x <= 65) ) {
// no statements to isolate execution time of the conditional and comparisons
}
if ( (x >= 20) && (z == 'F') ) {
//
}
if ( (x < 20) && (z == 'M') ) {
//
}
gettimeofday(&end , NULL);
lessifs += time_diff( start, end );
// More ifs, with nesting
// measure only the time spent in the conditional blocks
gettimeofday(&start , NULL);
if ( x < 20 ) {
if ( z == 'M' ) {
//
}
} else {
if ( x <= 65 && w == 1 ) {
//
}
if ( z == 'F' ) {
//
}
}
gettimeofday(&end, NULL);
moreifs += time_diff( start, end );
}
printf( "Original : %0.lf us\n", orig );
printf( "Less ifs, no nesting : %.0lf us\n" , lessifs );
printf( "More ifs, with nesting : %.0lf us\n" , moreifs );
return 0;
}
double time_diff(struct timeval x , struct timeval y)
{
double x_ms , y_ms , diff;
x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;
diff = (double)y_ms - (double)x_ms;
return diff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment