]> 4ch.mooo.com Git - 16.git/blob - src/lib/lib_head.c
added memory usage display~
[16.git] / src / lib / lib_head.c
1 #include "src/lib/lib_head.h"
2 \r
3 /* local function */\r
4 void wait(clock_t wait);
5 void* AllocateLargestFreeBlock(size_t* Size);
6 size_t GetFreeSize(void);\r
7 \r
8 /* Function: Wait **********************************************************\r
9 *\r
10 *     Parameters:    wait - time in microseconds\r
11 *\r
12 *     Description:    pauses for a specified number of microseconds.\r
13 *\r
14 */\r
15 void wait(clock_t wait){\r
16         clock_t goal;\r
17 \r
18         if(!wait) return;\r
19 \r
20         goal = wait + clock();\r
21         while((goal > clock()) && !kbhit()) ;\r
22 } /* End of wait */
23
24 void* AllocateLargestFreeBlock(size_t* Size)
25 {
26   size_t s0, s1;
27   void* p;
28
29   s0 = ~(size_t)0 ^ (~(size_t)0 >> 1);
30
31   while (s0 && (p = malloc(s0)) == NULL)
32     s0 >>= 1;
33
34   if (p)
35     free(p);
36
37   s1 = s0 >> 1;
38
39   while (s1)
40   {
41     if ((p = malloc(s0 + s1)) != NULL)
42     {
43       s0 += s1;
44       free(p);
45     }
46     s1 >>= 1;
47   }
48
49   while (s0 && (p = malloc(s0)) == NULL)
50     s0 ^= s0 & -s0;
51
52   *Size = s0;
53   return p;
54 }
55
56 size_t GetFreeSize(void)
57 {
58   size_t total = 0;
59   void* pFirst = NULL;
60   void* pLast = NULL;
61
62   for (;;)
63   {
64     size_t largest;
65     void* p = AllocateLargestFreeBlock(&largest);
66
67     if (largest < sizeof(void*))
68     {
69       if (p != NULL)
70         free(p);
71       break;
72     }
73
74     *(void**)p = NULL;
75
76     total += largest;
77
78     if (pFirst == NULL)
79       pFirst = p;
80
81     if (pLast != NULL)
82       *(void**)pLast = p;
83
84     pLast = p;
85   }
86
87   while (pFirst != NULL)
88   {
89     void* p = *(void**)pFirst;
90     free(pFirst);
91     pFirst = p;
92   }
93
94   return total;
95 }