Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <time.h>
  5.  
  6. typedef union {
  7. struct {
  8. float x, y;
  9. };
  10. struct {
  11. unsigned int next;
  12. };
  13. } item_t;
  14.  
  15. typedef struct {
  16. item_t* items;
  17. size_t size;
  18. size_t used;
  19. size_t num_inserts;
  20. size_t num_deletes;
  21. size_t num_allocations;
  22. } bulk_data_t;
  23.  
  24. void delete_item(bulk_data_t* bd, size_t index) {
  25. if (index >= bd->size) return;
  26. bd->items[index].next = bd->items[0].next;
  27. bd->items[0].next = index;
  28. bd->num_deletes++;
  29. }
  30.  
  31. size_t alloc_item(bulk_data_t* bd) {
  32. bd->num_inserts++;
  33. size_t slot = bd->items[0].next;
  34. bd->items[0].next = bd->items[slot].next;
  35. if (slot) return slot;
  36. if (bd->used < bd->size) {
  37. slot = bd->used++;
  38. return slot;
  39. }
  40. bd->size += 5;
  41. bd->items = reallocarray(bd->items, bd->size, sizeof(item_t));
  42. bd->num_allocations++;
  43. return bd->used++;
  44. }
  45.  
  46. int main() {
  47. srand(time(0));
  48.  
  49. bulk_data_t bd = { NULL, 1, 1, 1, 0, 0 };
  50. bd.items = reallocarray(bd.items, bd.size, sizeof(item_t));
  51. bd.items[0].next = 1;
  52. for (int i = 0; i < 1000; i++) {
  53. if (rand() % 2 == 0) {
  54. alloc_item(&bd);
  55. } else {
  56. delete_item(&bd, rand() % bd.size);
  57. }
  58. }
  59. printf(
  60. "%zu - %zu - %zu - %zu - %zu\n",
  61. bd.size,
  62. bd.used,
  63. bd.num_allocations,
  64. bd.num_inserts,
  65. bd.num_deletes
  66. );
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement