Добавлен pool со списками занятых/незанятых, в 6 раз быстрее std::vector.push_back() и в 3 раза быстрее malloc

This commit is contained in:
Kolan Sh 2011-04-29 15:41:02 +04:00
parent 03d20062b4
commit b8d84794f0
2 changed files with 131 additions and 2 deletions

View File

@ -0,0 +1,126 @@
#include <stdlib.h>
#include <stdio.h>
#define MAX_I 0x00ffffff
#define bool char
#define TRUE 1
#define FALSE 0
struct object_s {
char val;
};
struct block_s {
struct block_s *next;
struct block_s *prev;
struct object_s obj;
};
struct block_s pool[MAX_I];
struct block_s *free_pool = NULL,
*busy_pool = NULL;
/*
* инициализация пула
*/
void init()
{
size_t i;
size_t max_i = MAX_I - 1;
for (i = 1; i < max_i; i++) {
pool[i].prev = &pool[i - 1];
pool[i].next = &pool[i + 1];
}
pool[0].prev = NULL;
pool[0].next = &pool[1];
pool[MAX_I - 1].prev = &pool[MAX_I - 2];
pool[MAX_I - 1].next = NULL;
free_pool = &pool[0];
busy_pool = NULL;
}
#define MAX_B (pool + MAX_I * sizeof(struct block_s))
inline void *alloc()
{
if (!free_pool)
return NULL;
struct block_s *f1 = free_pool,
*f2 = free_pool->next,
*b1 = busy_pool;
// move one free block to busy list
// f1, b1
if (b1) {
f1->next = b1;
b1->prev = f1;
}
else
f1->next = NULL;
// f2
if (f2)
f2->prev = NULL;
// free_pool
free_pool = f2;
// busy_pool
busy_pool = f1;
return &f1->obj;
}
inline void free(void *p)
{
struct block_s *b1 = (struct block_s *)(p - 2 * sizeof(struct block_s *)),
*b0 = b1->prev,
*b2 = b1->next,
*f1 = free_pool;
// move one busy block to free list
// cut block from free list
if (b0)
b0->next = b2;
if (b2)
b2->prev = b0;
// f1, b1
if (f1) {
b1->next = f1;
f1->prev = b1;
}
else
b1->next = NULL;
// free_pool
free_pool = b2;
// busy_pool
if (busy_pool == b1)
busy_pool = b2;
}
int main()
{
unsigned long long i;
init();
for (i = 0; i < MAX_I; i++)
alloc();
return 0;
}

View File

@ -1,10 +1,13 @@
#!/bin/bash
echo "malloc_speed_test.c test:"
echo -e "\n\nmalloc_speed_test.c test:"
cc -O2 malloc_speed_test.c -o malloc_speed_test && time ./malloc_speed_test
echo -e "\n\nvector_add.cpp test:"
c++ -O2 vector_add.cpp -o vector_add && time ./vector_add
echo "pool1.c test:"
echo -e "\n\npool1.c test:"
cc -O2 pool1.c -o pool1 && time ./pool1
echo -e "\n\npool_list.c test:"
cc -O2 pool_list.c -o pool_list && time ./pool_list