Skip to content

Instantly share code, notes, and snippets.

@nkurz
Created October 8, 2014 21:27
Show Gist options
  • Save nkurz/0fbb2f2332a3142c9d15 to your computer and use it in GitHub Desktop.
Save nkurz/0fbb2f2332a3142c9d15 to your computer and use it in GitHub Desktop.
Identical loops that execute in different but consistent times
// gcc -std=gnu99 -O3 -Wall -Wextra same-function.c -o same-function
// Identical loops that execute in different but consistent times
#if COPY_AND_RUN_TO_TEST
for n in 0 1 2 3 4 5 6 7 8 9;
do echo same-function ${n}:;
/usr/bin/time -f "%e seconds" same-function ${n};
/usr/bin/time -f "%e seconds" same-function ${n};
/usr/bin/time -f "%e seconds" same-function ${n};
done
#endif
#include <stdio.h>
#include <stdint.h>
#define COMPILER_NO_INLINE __attribute__((noinline))
#define COUNT (1000 * 1000 * 1000)
volatile uint64_t counter = 0;
COMPILER_NO_INLINE void loop0(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop1(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop2(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop3(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop4(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop5(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop6(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop7(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop8(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
COMPILER_NO_INLINE void loop9(void) {
for (int j = COUNT; j != 0; j--) {
uint64_t val = counter;
val = val + 1;
counter = val;
}
return;
}
int main(int argc, char** argv) {
if (argc <= 1) goto die_usage;
char firstLetter = argv[1][0];
switch (firstLetter) {
case '0': loop0(); break;
case '1': loop1(); break;
case '2': loop2(); break;
case '3': loop3(); break;
case '4': loop4(); break;
case '5': loop5(); break;
case '6': loop6(); break;
case '7': loop7(); break;
case '8': loop8(); break;
case '9': loop9(); break;
default: goto die_usage;
}
return 0;
die_usage:
printf("Usage: [time] %s [0-9]\n", argv[0]);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment