memset+与bzero+置0的性能比较

小程序测试

#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <strings.h>

#define TIMEDIFF(s, e) (((e.tv_sec)-(s.tv_sec))*1000000 + (e.tv_usec) - (s.tv_usec))

int main()
{
    struct timeval s, e;
    char a[1024], b[1024*1024], c[1024*1024*4];

    gettimeofday(&s, NULL);
    bzero(a, sizeof(a));
    gettimeofday(&e, NULL);
    printf("bzero 1k: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    bzero(b, sizeof(b));
    gettimeofday(&e, NULL);
    printf("bzero 1m: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    bzero(c, sizeof(c));
    gettimeofday(&e, NULL);
    printf("bzero 4M: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    memset(a, 0, sizeof(a));
    gettimeofday(&e, NULL);
    printf("memset 1k: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    memset(b, 0, sizeof(b));
    gettimeofday(&e, NULL);
    printf("memset 1M: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    memset(c, 0, sizeof(c));
    gettimeofday(&e, NULL);
    printf("memset 4M: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    for(int i=0; i<sizeof(a); ++i)
        a[i]=0;
    gettimeofday(&e, NULL);
    printf("for 1k: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    for(int j=0; j<sizeof(b); ++j)
        b[j]=0;
    gettimeofday(&e, NULL);
    printf("for 1M: %ld\n", TIMEDIFF(s, e));

    gettimeofday(&s, NULL);
    for(int k=0; k<sizeof(c); ++k)
        c[k]=0;
    gettimeofday(&e, NULL);
    printf("for 4M: %ld\n", TIMEDIFF(s, e));
}

测试1

测试2

自我感觉,总的来说还是memset()更好一些。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值