随笔 - 2  文章 - 0  trackbacks - 0
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

常用链接

留言簿

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

memcached修改后的内存池

修改了memcached内存池的源代码。支持单个size的slab的分配,以及多级slab分配。 

以下是测试代码:
 
#include "slabs.h"
#include <stdio.h>
#include <sys/time.h>
#include<stdlib.h>

typedef struct item
{
    int x;
    double y;
    char z[248];
    char zz[1324];
}item;

static int xx = 0;
static double yy = 1.0;
static item *item_list[1000];

long time_interval( struct timeval tv );

int main()
{
    struct    timeval t_start;
    gettimeofday(&t_start, NULL);

    slabs_init( 1024*1024*100, 1.0, sizeof(item), 1 );
    for( int i = 0; i < 100000; ++i)
    {
        for(int j = 0; j < 1000; ++j)
        {
               
            //item * pItem = (item *)do_slabs_alloc( sizeof(item), slabs_clsid(sizeof(item) ));            
            item * pItem = (item *)malloc(sizeof(item));
            if(pItem == NULL)
            {
                printf("do_slabs_alloc error\n");
                return -1;
            }

            pItem->x = ++xx;
            pItem->y = yy + 1.0;

            item_list[j] = pItem;

        }
        for(int k = 0; k < 1000; ++k)
        {
            //do_slabs_free(item_list[k], sizeof(item), slabs_clsid(sizeof(item) ));
            free(item_list[k]);
        }
    }

    long int tm = time_interval( t_start);

    printf("\ntime used :%d\n", tm);

    return 0;

}

long time_interval( struct timeval tv )
{
    struct timeval now;
    gettimeofday(&now, NULL);

    long sec = now.tv_sec - tv.tv_sec;
    long usec = now.tv_usec - tv.tv_usec;
    return sec * 1000 + usec / 1000;
}

测试结果:

对于使用malloc, free和do_slabs_alloc,do_slabs_free     
1)当外层循环10000次时,分别耗时6992ms,547ms
2)当外层循环100000次时,分别耗时69665ms,5442ms

改变item的结构:

typedef struct item
{
    int x;
    double y;
    char z[248];
}item;

1)当外层循环10000次时,分别耗时1536ms,535ms
2)当外层循环100000次时,分别耗时15414ms,5352ms

综上:系统的malloc函数对于size很敏感,如果size较小,那么内存分配的时间需要很长,因为它需要计算,并且可能操作多个链表(malloc函数自己也对内存分级)。而内存池则对大小不敏感,对于大内存块和小内存块来说速度基本上同样快。
posted @ 2009-09-17 00:06 clj 阅读(482) | 评论 (0)编辑 收藏

举一个例子来说明。

父亲叫儿子去请叔叔来下棋,儿子需要开车去叔叔家。

同步:父亲在家什么事也不能做,在家等着。叔叔回来了儿子敲门通知父亲。
异步:父亲有一大堆其它事情要忙,打发儿子完儿子后接着忙一大堆其它的事情,等儿子回来了敲门通知父亲。

上面的同步和异步都使用到了非阻塞操作。
同步和异步的区别就在于:同步必须等到操作的结果,否则其它事都做不了;异步体现在操作发起后不用等待的结果,接着做其它事情,等操作结果出来了会受到通知并作相应处理。


Douglas博士的解释如下:

 AIO is "asynchronous I/O", i.e., the operation is invoked asynchronously and control returns to the client while the OS kernel processes the I/O request.?When the operation completes there is some mechanism for the client to retrieve the results.

 Non-blocking I/O tries an operation (such as a read() or write()) and if it the operation would block (e.g., due to flow control on a TCP connection or due to lack of data in a socket), the call returns -1 and sets errno to EWOULDBLOCK.

posted @ 2009-09-11 00:32 clj 阅读(1368) | 评论 (0)编辑 收藏
仅列出标题