Advertisement
Guest User

Untitled

a guest
Dec 21st, 2014
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5. #include <sys/mman.h>
  6.  
  7. #define MAX_SHIFT 24
  8. #define REPETITIONS 10
  9. #define ITERATIONS (1 << 20)
  10.  
  11. void *mmalloc(size_t length)
  12. {
  13. void *addr = mmap(NULL, length, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  14. if(addr == (void*)-1)
  15. {
  16. perror("mmap");
  17. exit(EXIT_FAILURE);
  18. }
  19. return addr;
  20. }
  21.  
  22. void mfree(void *addr, size_t length)
  23. {
  24. if(-1 == munmap(addr, length))
  25. {
  26. perror("munmap");
  27. exit(EXIT_FAILURE);
  28. }
  29. }
  30.  
  31. void yates_shuffle(size_t volatile *a, size_t length)
  32. {
  33. size_t *t = calloc(length, sizeof(size_t));
  34. size_t i;
  35. for(i = 0; i < length; i++)
  36. t[i] = i;
  37. for(i = length; i;)
  38. {
  39. size_t j = rand() % i;
  40. i--;
  41. size_t tmp = t[i];
  42. t[i] = t[j];
  43. t[j] = tmp;
  44. }
  45. for(i = 0; i < length - 1; i++)
  46. a[t[i]] = t[i + 1];
  47. a[t[length - 1]] = t[0];
  48. }
  49.  
  50. long long int test(size_t length, int n)
  51. {
  52. size_t volatile *window = mmalloc(length * sizeof(size_t));
  53. yates_shuffle(window, length);
  54. struct timespec s, e;
  55. size_t ptr = 0;
  56. int i;
  57. clock_gettime(CLOCK_REALTIME, &s);
  58. for(i = 0; i < n; i++)
  59. ptr = window[ptr];
  60. clock_gettime(CLOCK_REALTIME, &e);
  61. mfree((void *)window, length * sizeof(size_t));
  62. return (e.tv_sec - s.tv_sec) * 1000000 + ((signed long long int)e.tv_nsec - (signed long long int)s.tv_nsec) / 1000;
  63. }
  64.  
  65. int main()
  66. {
  67. int i;
  68. for(i = 1; i <= MAX_SHIFT; i++)
  69. {
  70. long long int sum = 0;
  71. printf("%10lld octets (%11lld bytes): ", 1LL << i, sizeof(size_t) * (1LL << i));
  72. fflush(stdout);
  73. int j;
  74. for(j = 0; j < REPETITIONS; j++)
  75. {
  76. sum += test(1 << i, ITERATIONS);
  77. printf(".");
  78. fflush(stdout);
  79. }
  80. printf(" %11lld microseconds\n", sum / REPETITIONS);
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement