性能杀手snprintf

需求

在嵌入式软件开发中,标准库中的sprintfsnprintf函数,对于格式转换十分方便,其将格式化的数据写入到指定的字符串缓冲区中。

现在有一个需求将整型数组转换成字符串形式:

// 待转换的数组
const uint16_t data[] = {
    1, 3, 6, 1, 4, 1, 4128, 2200, 10
};
// 转换后的期望字符串
const char *expected_str = "1.3.6.1.4.1.4128.2200.10.";

有几种实现方式:snprintf,itoa,自实现,接下就编写代码实际测试一下性能。

实现

snprintf

int test_snprintf(const uint16_t *data, size_t data_num, char *buf, size_t buf_size)
{
    int ret;
    size_t n = buf_size;

    for (size_t i = 0; i < data_num; i++) {
        ret = snprintf(buf, n, "%d.", data[i]);
        n -= ret;
        buf += ret;
    }

    return (buf_size - n);
}

atoi

由于atoi不是标准库中的函数,我实际测试gcc采用的glibc编译失败。

int test_itoa(const uint16_t *data, size_t data_num, char *buf, size_t buf_size)
{
    char *p = buf;
    size_t n;

    memset(buf, '\0', buf_size);
    
    for (size_t i = 0; i < data_num; i++) {
        p = itoa(data[i], p, 10);
        n = strlen(p);
        p += n;
        *p++ = '.';
    }

    return (p - buf);
}

自实现

由于我们知道数组是无符号整型,可以自己实现一个简单的转换函数。

unsigned int uint_to_str(unsigned int num, char *str) 
{
    int i = 0;
    char temp[32];
 
    // 处理0的特殊情况
    if (num == 0) {
        str[0] = '0';
        str[1] = '\0';
        return 1;
    }
 
    // 将数字逆序存储到临时数组中
    while (num > 0) {
        temp[i++] = (num % 10) + '0';
        num /= 10;
    }
 
    // 将临时数组中的字符逆序复制到目标字符串中
    for (int j = 0; j < i; j++) {
        str[j] = temp[i - 1 - j];
    }
    
    // 添加字符串终止符
    str[i] = '\0'; 

    return i;
}

int test_uint_to_str(const uint16_t *data, size_t data_num, char *buf, size_t buf_size)
{
    int ret;
    size_t n = buf_size;

    for (size_t i = 0; i < data_num; i++) {
        ret = uint_to_str(data[i], buf);
        n -= ret;
        buf += ret;
        *buf++ = '.';
    }

    return (buf_size - n);
}

完整代码

完整的测试代码如下:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>

int test_snprintf(const uint16_t *data, size_t data_num, char *buf, size_t buf_size)
{
    int ret;
    size_t n = buf_size;

    for (size_t i = 0; i < data_num; i++) {
        ret = snprintf(buf, n, "%d.", data[i]);
        n -= ret;
        buf += ret;
    }

    return (buf_size - n);
}

// int test_itoa(const uint16_t *data, size_t data_num, char *buf, size_t buf_size)
// {
//     char *p = buf;
//     size_t n;

//     memset(buf, '\0', buf_size);
    
//     for (size_t i = 0; i < data_num; i++) {
//         p = itoa(data[i], p, 10);
//         n = strlen(p);
//         p += n;
//         *p++ = '.';
//     }

//     return (p - buf);
// }

unsigned int uint_to_str(unsigned int num, char *str) 
{
    int i = 0;
    char temp[32];
 
    // 处理0的特殊情况
    if (num == 0) {
        str[0] = '0';
        str[1] = '\0';
        return 1;
    }
 
    // 将数字逆序存储到临时数组中
    while (num > 0) {
        temp[i++] = (num % 10) + '0';
        num /= 10;
    }
 
    // 将临时数组中的字符逆序复制到目标字符串中
    for (int j = 0; j < i; j++) {
        str[j] = temp[i - 1 - j];
    }

    // 添加字符串终止符
    str[i] = '\0';

    return i;
}

int test_uint_to_str(const uint16_t *data, size_t data_num, char *buf, size_t buf_size)
{
    int ret;
    size_t n = buf_size;

    for (size_t i = 0; i < data_num; i++) {
        ret = uint_to_str(data[i], buf);
        n -= ret;
        buf += ret;
        *buf++ = '.';
    }

    return (buf_size - n);
}


int main(int *argc, char **argv)
{
    const uint16_t data[] = {
        1, 3, 6, 1, 4, 1, 4128, 2200, 10
    };
    const size_t data_num = sizeof(data) / sizeof(data[0]);
    const char *expected_str = "1.3.6.1.4.1.4128.2200.10.";
    char buf[128];
    const size_t buf_size = sizeof(buf);

    struct timeval start, end;
    long elapsed[3];

    /* snprintf */
    gettimeofday(&start, NULL);
    test_snprintf(data, data_num, buf, buf_size);
    gettimeofday(&end, NULL);
    elapsed[0] = (end.tv_sec - start.tv_sec) * 1e6 + (end.tv_usec  - start.tv_usec );
    if (strncmp(expected_str, buf, strlen(expected_str))) {
        printf("Failed to test snprintf\n");
        return -1;
    }

    /* itoa */
    // gettimeofday(&start, NULL);
    // test_itoa(data, data_num, buf, buf_size);
    // gettimeofday(&end, NULL);
    // elapsed[1] = (end.tv_sec - start.tv_sec) * 1e6 + (end.tv_usec  - start.tv_usec );
    // if (strncmp(expected_str, buf, strlen(expected_str))) {
    //     printf("Failed to test itoa\n");
    //     return -1;
    // }

    /* uint to str */
    gettimeofday(&start, NULL);
    test_uint_to_str(data, data_num, buf, buf_size);
    gettimeofday(&end, NULL);
    elapsed[2] = (end.tv_sec - start.tv_sec) * 1e6 + (end.tv_usec  - start.tv_usec );
    if (strncmp(expected_str, buf, strlen(expected_str))) {
        printf("Failed to test uint_to_str\n");
        return -1;
    }

    printf("%s\t%10ldus\n", "snprintf", elapsed[0]);
    // printf("%s\t%8ld\n", "itoa", elapsed[1]);
    printf("%s\t%10ldus\n", "uint_to_str", elapsed[2]);

    return 0;
}

在PC上测试时间消耗如下:

snprintf                21us
uint_to_str              1us

可以看出snprintf函数竟然是uint_to_str的21倍,性能差距十分明显。因此虽然snprintf/sprintf使用起来方便,但如果使用场景固定,尤其是在意性能的场景,自己实现带来的性能提升十分可观。

最后看下大神对比了C++下各种实现整型到字符串的转换效率:

C++下整型转字符串对比

参考

  1. sprintf函数
  2. 字符串拷贝函数memcpy()、strncpy()和snprintf()性能之比较
  3. Fast integer to string conversion in C++
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值