C 慢速缓冲区访问 [已关闭]

问题描述 投票:0回答:1

我有两个具有类似任务的代码片段。

以下代码需要四秒钟:

while(1)
{
    fputs(erz_aint2hex(buffer[write_helper++]), fp);
    if(write_helper > _size) { if(enable_output) erz_output(white, LOCAL_FUNCTION_NAME, "Write data to file\r\n"); break; }
}

第二个代码需要15分钟以上:

while(1)
{
    strcat(buf_ret, (erz_aint2hex(buffer[write_helper++])));            
    if(write_helper > _size) { if(enable_output) erz_output(white, LOCAL_FUNCTION_NAME, "Write data to buffer\r\n"); break; }
}

buf_ret
buffer
是 malloc 字符数组。第一个代码将任何输入文件转换为十六进制格式的新文件。第二个代码执行相同的操作,但将内容存储在缓冲区中。输入文件有 7mb,转换后有 15mb。为什么第二个代码这么慢?我该怎么做才能让它更快?

我也尝试了

snprintf(hexhelper, sizeof(hexhelper), "%X", buffer[write_helper++]);
strncat()
strcat()
这么慢吗?

c 64-bit
1个回答
0
投票

strcat
需要在每次调用时查找
buf_ret
中包含的字符串末尾(即尾随空字节),所以是的,
buf_ret
增长的时间越长,它就会变得越来越慢。

© www.soinside.com 2019 - 2024. All rights reserved.