Skip to content

Instantly share code, notes, and snippets.

@arpitbbhayani
Created September 4, 2019 16:27
Show Gist options
  • Save arpitbbhayani/d06cb7f4bb0cfdc8daa596dd77e8de10 to your computer and use it in GitHub Desktop.
Save arpitbbhayani/d06cb7f4bb0cfdc8daa596dd77e8de10 to your computer and use it in GitHub Desktop.
Benchmark - Stopping loop iteration
#include <cstdio>
#include <ctime>
#include <sys/time.h>
#define SIZE 1000000001
char str[SIZE];
void with_break(char *str) {
bool a_found = false;
for (int i = 0; str[i]; i++) {
if (str[i] == 'a') {
a_found = true;
break;
}
}
}
void with_condition(char *str) {
bool a_found = false;
for (int i = 0; a_found == false && str[i]; i++) {
if (str[i] == 'a') {
a_found = true;
}
}
}
void populate(int size) {
for(int i = 0; i < size; i++) {
str[i] = i == size/2 ? 'a' : 'b';
}
str[size] = NULL;
}
float time_it(void (*fn)(char *)) {
struct timeval start_time, end_time;
gettimeofday(&start_time, 0);
fn(str);
gettimeofday(&end_time, 0);
return (end_time.tv_sec - start_time.tv_sec) * 1000.0f + (end_time.tv_usec - start_time.tv_usec) / 1000.0f;
}
int get_size(int iteration) {
switch (iteration) {
case 0: return 500;
case 1: return 1000;
case 2: return 10000;
case 3: return 100000;
case 4: return 1000000;
case 5: return 10000000;
case 6: return 50000000;
case 7: return 100000000;
case 8: return 500000000;
case 9: return 1000000000;
}
return 0;
}
int main() {
printf("iteration,with_break,with_condition,percent,elements\n");
for (int iteration = 0; iteration < 10; iteration ++) {
int size = get_size(iteration);
populate(size);
for (int repetition = 0; repetition < 5; repetition++) {
float time_break = time_it(with_break);
float time_condition = time_it(with_condition);
printf("%d", iteration);
printf(",%f", time_break);
printf(",%f", time_condition);
printf(",%f", (((time_condition - time_break) * 100)/(1.0 * time_break)));
printf(",%d\n", size);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment