-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_consumption.c
More file actions
45 lines (40 loc) · 991 Bytes
/
Copy pathmemory_consumption.c
File metadata and controls
45 lines (40 loc) · 991 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
void print_memory_usage()
{
struct mallinfo info = mallinfo();
printf("Memory usage: %.2f MB\n", (float)info.uordblks / (1024 * 1024));
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s <memory in MB>\n", argv[0]);
return 1;
}
int memory_in_mb = atoi(argv[1]);
if (memory_in_mb > 2)
{
printf("Tips: %s <Memory must not be larger than 2>\n", argv[0]);
return 1;
}
size_t size = memory_in_mb * 1024 * 1024; // Convert MB to bytesS
int *block[20];
printf("malloc:\n");
for (int i = 0; i < 20; ++i)
{
block[i] = malloc(size / 20);
sleep(0.5); // Adjusted sleep time for better visibility
print_memory_usage();
}
printf("\nfree:\n");
for (int i = 0; i < 20; ++i)
{
free(block[i]);
sleep(0.2);
print_memory_usage();
}
return 0;
}