Guest User

direct code search vs linear search

a guest
Oct 22nd, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. #include <assert.h>
  2.  
  3. #include <dlfcn.h>
  4. #include <limits.h>
  5. #include <stdint.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8.  
  9. #include <sys/time.h>
  10.  
  11.  
  12. #define SETSIZE 10
  13. #define NRUNS   10000000
  14.  
  15. typedef int (*func)(uint32_t);
  16.  
  17. static func
  18. getfunc(uint32_t *set)
  19. {
  20.     size_t i;
  21.     FILE *f;
  22.     char path[PATH_MAX];
  23.     char *pres;
  24.     void *dlhandle;
  25.     func r;
  26.     char *error;
  27.  
  28.     f = fopen("dcode.c", "w");
  29.     assert(f != NULL);
  30.     fprintf(f, "#include <stdint.h>\n\n");
  31.     fprintf(f, "int set_test(uint32_t key) {\n");
  32.     for (i=0; i<SETSIZE; i++) {
  33.         fprintf(f, " if (key == %d) return 1;\n", set[i]);
  34.     }
  35.     fprintf(f, " return 0;\n}\n");
  36.     fclose(f);
  37.  
  38.     system("cc -s -O3 -c dcode.c");
  39.     system("cc -shared  -Wl,-soname,libdcst.so -o libdcst.so dcode.o");
  40.  
  41.     pres = realpath("libdcst.so", path);
  42.     assert(pres != NULL);
  43.  
  44.     dlhandle = dlopen(path, RTLD_NOW);
  45.     assert(dlhandle != NULL);
  46.  
  47.     *(void **) &r = dlsym(dlhandle, "set_test");
  48.     if ((error = dlerror()) != NULL)  {
  49.         fprintf(stderr, "%s\n", error);
  50.         exit(EXIT_FAILURE);
  51.     }
  52.  
  53. /*  dlclose(dlhandle);*/
  54.     return r;
  55. }
  56.  
  57.  
  58. int
  59. main()
  60. {
  61.     uint32_t set[SETSIZE];
  62.     size_t i;
  63.     func f;
  64.     struct timeval begin, end;
  65.     int acc;
  66.  
  67.     for (i=0; i<SETSIZE; i++) {
  68.         set[i] = rand();
  69.     }
  70.  
  71.     f = getfunc(set);
  72.  
  73.     gettimeofday(&begin, NULL);
  74.     acc = 0;
  75.     for (i=0; i<NRUNS; i++) {
  76.         uint32_t sample;
  77.  
  78.         sample = rand();
  79.         if (f(sample)) acc++;
  80.     }
  81.     gettimeofday(&end, NULL);
  82.     printf("direct code: %f secs\n", ((double)((end.tv_sec - begin.tv_sec)*1000000 + end.tv_usec - begin.tv_usec)) / 1000000.0);
  83.  
  84.     acc = 0;
  85.     gettimeofday(&begin, NULL);
  86.     for (i=0; i<NRUNS; i++) {
  87.         uint32_t sample;
  88.         int j;
  89.  
  90.         sample = rand();
  91.         for (j=0; j<SETSIZE; j++) {
  92.             if (set[j] == sample) acc++;
  93.         }
  94.     }
  95.     gettimeofday(&end, NULL);
  96.     printf("linear search: %f secs, acc=%d\n", ((double)((end.tv_sec - begin.tv_sec)*1000000 + end.tv_usec - begin.tv_usec)) / 1000000.0, acc);
  97.  
  98.     return EXIT_SUCCESS;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment