我正在编写一个小程序,它打印分配内存所花费的时间。我想稍后释放内存,所以我想将它保存在一个数组中,但是因为我可以循环多次,我想创建一个动态数组来存储分配的内存中的所有地址。这是我的初始化代码:
static __init int init_kmalloc(void)
{
int size = sizeof(char*);
char *buffer = kmalloc_array(loop_cnt, size, GFP_KERNEL);
unsigned int i = 0;
printk(KERN_DEBUG "Allocating %d times the memory size of %d\n", loop_cnt, alloc_size);
while(i < loop_cnt)
{
unsigned long long start;
unsigned long long stop;
start = get_rdtsc();
buffer[i] = kmalloc(alloc_size, GFP_KERNEL);
stop = get_rdtsc();
printk(KERN_DEBUG "%i: It took %lld ticks to allocate the memory\n", i, stop - start);
i++;
}
while(i > 0)
{
kfree(buffer[i]);
printk(KERN_DEBUG "Cleared\n");
i--;
}
return 0;
}