Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active September 19, 2022 15:10
Show Gist options
  • Save theoknock/36b1b7582791983820bf60b52b661366 to your computer and use it in GitHub Desktop.
Save theoknock/36b1b7582791983820bf60b52b661366 to your computer and use it in GitHub Desktop.
Test the efficiency of recursive functions and loop constructs and conditionals
#import "Clocking.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define CONDITION(x) ((clock_t)nil ^ x)
#define DECREMENT(x) (x = ~-x)
#define ADJUST_TIME(x) x / CLOCKS_PER_SEC
#define TOTAL_TIME(a,z) ADJUST_TIME((double)(z - a))
#define PRINT_RESULT(a,z) printf("\n%lu iterations:\n\tbeg %f\n\tend %f\n\t----------------\n\tsum\t%f\n------------------------- %f\n\n", (unsigned long)a, ADJUST_TIME(a), ADJUST_TIME(z), TOTAL_TIME(a, z), (TOTAL_TIME(a, z)/a) * CLOCKS_PER_SEC)
@interface Clocking ()
@end
@implementation Clocking
- (void)clock_tests {
[super viewDidLoad];
{
clock_t start_t;
clock_t end_t =
({
clock_t count = (start_t = clock());
for (; CONDITION(count); ) {
DECREMENT(count);
}
clock();
});
PRINT_RESULT((double)start_t, (double)end_t);
}
{
clock_t start_t;
clock_t end_t =
({
clock_t count = (start_t = clock());
do {
DECREMENT(count);
} while (CONDITION(count));
clock();
});
PRINT_RESULT((double)start_t, (double)end_t);
}
{
clock_t start_t, end_t;
({
static clock_t (^recursive_f)(clock_t);
static clock_t (^ const * recursive_t)(clock_t) = &recursive_f;
end_t = (recursive_f = ^ (clock_t count) {
return (CONDITION(count)) ? (*recursive_t)(DECREMENT(count)) : (clock_t)clock();
})(({
start_t = clock();
start_t;
}));
});
PRINT_RESULT((double)start_t, (double)end_t);
}
}
@end
@theoknock
Copy link
Author

theoknock commented Sep 15, 2022

Sample console output:

161258 iterations:
beg 0.161258
end 0.161393
----------------
sum 0.000135
------------------------- 0.000837

161408 iterations:
beg 0.161408
end 0.161540
----------------
sum 0.000132
------------------------- 0.000818

161543 iterations:
beg 0.161543
end 0.162586
----------------
sum 0.001043
------------------------- 0.006456

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