Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C slow buffer access

I have two code snippets with an similar task.

Following code needs four seconds:

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; }
}

The second code needs above 15 minutes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 and buffer are malloc char arrays. The first code stores any input file convertet to a new file in hex format. The second code do the same but stores the content in a buffer. The input file have 7mb and converted 15mb. Why is the second code so slow? And what can i do to make it faster?

I also tried snprintf(hexhelper, sizeof(hexhelper), "%X", buffer[write_helper++]); and strncat().
Is strcat() so slow?

>Solution :

strcat will need to look for the end of the string contained in buf_ret (that is, the trailing null byte) on every call, so yeah, it’s going to be slower and slower the longer buf_ret grows.

Something like

char *buf_w = buf_ret;
while (1) {
  char *hex = erz_aint2hex(buffer[write_helper++]);
  *buf_w++ = hex[0];  // assumes hex is 
  *buf_w++ = hex[1];  // 2 bytes long

  if (write_helper > _size) {
    if (enable_output)
      erz_output(white, LOCAL_FUNCTION_NAME, "Write data to buffer\r\n");
    break;
  }
}

would probably be a lot faster. (YMMV, beware, no bounds checks here.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading