字符串拷贝函数的性能比较

本文通过实验对比了strcpy、strncpy、snprintf三种字符串操作函数在无编译器优化情况下的性能表现,实验结果显示memcpy性能最优,snprintf次之,strncpy性能最差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先上结论:

memcpy性能 优于 snprintf性能 优于 strncpy性能

memcpy性能略优于snprintf,strncpy比前两者慢的非常多,基本上是捞不回来了。


编译器:gcc version 3.4.5 (a little old fashion偷笑)

没有编译器优化

测试代码:

int strncpy_test() {
    char src[] = "1234567890";
    char dest[2048];
    int len = 0;

    for(int i = 0; i < 10000000; ++i) {
        memset(dest, 0, sizeof(dest));
        strncpy(dest, src, sizeof(dest));
    }

    return 0;
}

int mempcy_test(){
    char src[] = "1234567890";
    char dest[2048];
    int len = 0;
    for(int i = 0; i < 10000000; ++i){
        memset(dest, 0, sizeof(dest));
        len = strlen(src);
        len = sizeof(dest) - 1 > len? len: sizeof(dest) -1;
        memcpy(dest, src, len);
        dest[len] = '\0';
    }
    return 0;
}

int snprintf_test() {
    char src[] = "1234567890";
    char dest[2048];
    int len = 0;

    for(int i = 0; i < 10000000; ++i) {
        memset(dest, 0, sizeof(dest));
        snprintf(dest, sizeof(dest), "%s", src);
    }

    return 0;
}

int main() {
    Timer t;
    t.start();
    mempcy_test();
    t.finish();
    t.print("mempcy_test");

    t.start();
    strncpy_test();
    t.finish();
    t.print("strncpy_test");

    t.start();
    snprintf_test();
    t.finish();
    t.print("snprintf_test");

    return 0;
}
其中Timmer是自己包的一个计时类,单位是us。
输出:
mempcy_test time use   : 1543216
strncpy_test time use  : 18600572
snprintf_test time use : 2155672





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值