简体   繁体   English

strncpy需要很长时间

[英]strncpy taking a long time

I have recently encountered some legacy code and noticed that sometimes (not always) the following code snippet takes a very long time to execute. 我最近遇到了一些旧代码,并注意到有时(并非总是)以下代码片段需要很长时间才能执行。

#define NUM_OF_RECORDS 100000
char* pzBuffer = new char[NUM_OF_RECORDS + 1];
strncpy(pzBuffer, "", NUM_OF_RECORDS);

The objective seems to be to initialize the pzBuffer and I agree that memcpy or memset would be a better choice. 目的似乎是初始化pzBuffer,我同意memcpy或memset是更好的选择。 I'm trying to figure out why it's taking time and if the usage here is correct. 我试图弄清楚为什么要花时间,以及这里的用法是否正确。

using memset() could do better due to the following reason: 由于以下原因,使用memset()可能会更好:

1) strncpy() works at individual 'char' level meaning it would iterate over all chars one by one ( ~NUM_OF_RECORDS iterations in your case). 1) strncpy()在单个“字符”级别工作,这意味着它将一一遍历所有字符(在您的情况下为~NUM_OF_RECORDS迭代)。

2) memset() works at block level where a block consists of say N bytes. 2) memset()在块级工作,其中一个块由N个字节组成。 Although this means going over individual bytes of a block, this function is designed for optimizations wrt large block sizes, which often result in better performance when blocks of large sizes are involved. 尽管这意味着要遍历一个块的各个字节,但此功能是为优化大块尺寸而设计的,当涉及大块的块时,通常可以提高性能。

I would recommend creating variants of your code 1)using memset 2)other with strncpy. 我建议创建代码变体1)使用内存集2)其他与strncpy。 Then, compile both of them to generate assembly code, and find out the difference between instructions. 然后,编译它们两个以生成汇编代码,并找出指令之间的差异。

http://unix.superglobalmegacorp.com/BSD4.4Lite/newsrc/libkern/strncpy.c.html http://unix.superglobalmegacorp.com/BSD4.4Lite/newsrc/libkern/strncpy.c.html

loks like the standard implementation of strncpy fills all remaining elements of the array with zeros, no matter what. 像strncpy的标准实现这样的lok会用零填充数组的所有剩余元素,无论如何。 So, it takes time doing that,. 因此,这样做需要时间。

    do {
        if ((*d++ = *s++) == 0) {
            /* NUL pad the remaining n-1 bytes */
            while (--n != 0)
                *d++ = 0;
            break;
        }
    } while (--n != 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM