malloc_speed.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (C) 2013 Martin Willi
  3. * Copyright (C) 2013 revosec aG
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the
  7. * Free Software Foundation; either version 2 of the License, or (at your
  8. * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
  9. *
  10. * This program is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  12. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  13. * for more details.
  14. */
  15. #include <stdio.h>
  16. #include <time.h>
  17. #include <library.h>
  18. #include <utils/debug.h>
  19. #ifdef HAVE_MALLINFO
  20. #include <malloc.h>
  21. #endif /* HAVE_MALLINFO */
  22. static void start_timing(struct timespec *start)
  23. {
  24. clock_gettime(CLOCK_THREAD_CPUTIME_ID, start);
  25. }
  26. static double end_timing(struct timespec *start)
  27. {
  28. struct timespec end;
  29. clock_gettime(CLOCK_THREAD_CPUTIME_ID, &end);
  30. return (end.tv_nsec - start->tv_nsec) / 1000000000.0 +
  31. (end.tv_sec - start->tv_sec) * 1.0;
  32. }
  33. static void print_mallinfo()
  34. {
  35. #ifdef HAVE_MALLINFO
  36. struct mallinfo mi = mallinfo();
  37. printf("malloc: sbrk %d, mmap %d, used %d, free %d\n",
  38. mi.arena, mi.hblkhd, mi.uordblks, mi.fordblks);
  39. #endif /* HAVE_MALLINFO */
  40. }
  41. #define ALLOCS 1024
  42. #define ROUNDS 2048
  43. int main(int argc, char *argv[])
  44. {
  45. struct timespec timing;
  46. int i, round;
  47. void *m[ALLOCS];
  48. /* a random set of allocations we test */
  49. int sizes[16] = { 1, 13, 100, 1000, 16, 10000, 50, 17,
  50. 123, 32, 8, 64, 8096, 1024, 123, 9 };
  51. library_init(NULL, "malloc_speed");
  52. atexit(library_deinit);
  53. print_mallinfo();
  54. start_timing(&timing);
  55. for (round = 0; round < ROUNDS; round++)
  56. {
  57. for (i = 0; i < ALLOCS; i++)
  58. {
  59. m[i] = malloc(sizes[(round + i) % countof(sizes)]);
  60. }
  61. for (i = 0; i < ALLOCS; i++)
  62. {
  63. free(m[i]);
  64. }
  65. }
  66. printf("time for %d malloc/frees, repeating %d rounds: %.4fs\n",
  67. ALLOCS, ROUNDS, end_timing(&timing));
  68. print_mallinfo();
  69. return 0;
  70. }