Advertisement
Guest User

Measure the cost of bounds checking

a guest
Jul 10th, 2012
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. #define SIZE 1000 * 1000 * 400
  6.  
  7. double timing(clock_t start, clock_t finish) {
  8.   return ((double) finish - start) / CLOCKS_PER_SEC;
  9. }
  10.  
  11.  
  12. int main() {
  13.   int *a = calloc(SIZE, sizeof(int));
  14.   /* walk over everything once to normalize for cache effects */
  15.   for (int i = 0; i < SIZE; i++) { int z = a[i]; }
  16.  
  17.   /* The unchecked version */
  18.   clock_t start_unchecked = clock();
  19.   for (int i = 0; i < SIZE; i++) {
  20.       int z = a[i];
  21.   }
  22.   clock_t finish_unchecked = clock();
  23.  
  24.   /* walk over everything once to normalize for cache effects */
  25.   for (int i = 0; i < SIZE; i++) { int z = a[i]; }
  26.  
  27.   /* The unchecked version */
  28.   clock_t start_checked = clock();
  29.   for (int i = 0; i < SIZE; i++) {
  30.     if (i < SIZE) {
  31.       int z = a[i];
  32.     }
  33.   }
  34.   clock_t finish_checked = clock();
  35.  
  36.   printf("Checked: %f, Unchecked: %f",
  37.          timing(start_unchecked, finish_unchecked),
  38.          timing(start_checked, finish_checked));
  39.   return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement