[Asterisk-Dev] [RFC] strncpy -> ast_copy_string

Kevin P. Fleming kpfleming at digium.com
Sun May 1 23:18:20 MST 2005


Kevin P. Fleming wrote:

> In the vast majority of cases in my test Asterisk system, the strncpy 
> calls are copying strings that consume 25% or less of the target buffer, 
> and in a great deal of cases (the dialplan specifically) they are 
> consuming less than 10% of the target buffer. strncpy is writing zeroes 
> into 75%/90% of the buffer when it's totally unnecessary.

And here's real-world numbers. This is compiled with gcc-3.3.4, running 
on an Athlon XP 2400+ with DDR-400 RAM. The test programs do 10,000,000 
copies of a 20-character constant string (plus the terminating null) 
into an 80-character buffer. The programs were compiled with -O6.

kpfleming at jeeves:~> time ./test_copy_string

real    0m0.662s
user    0m0.549s
sys     0m0.006s
kpfleming at jeeves:~> time ./test_copy_string

real    0m0.621s
user    0m0.545s
sys     0m0.007s
kpfleming at jeeves:~> time ./test_copy_string

real    0m0.620s
user    0m0.548s
sys     0m0.004s
kpfleming at jeeves:~> time ./test_copy_string

real    0m0.622s
user    0m0.549s
sys     0m0.007s
kpfleming at jeeves:~> time ./test_strncpy

real    0m1.438s
user    0m1.245s
sys     0m0.009s
kpfleming at jeeves:~> time ./test_strncpy

real    0m1.409s
user    0m1.246s
sys     0m0.014s
kpfleming at jeeves:~> time ./test_strncpy

real    0m1.545s
user    0m1.244s
sys     0m0.009s

As you can clearly see, ast_copy_string takes about 40% of the CPU time 
that strncpy does, for the same job. That's using the open-coded version 
with no processor optimization other than what GCC does on its own.

If the ratio of source string length to destination buffer length 
increases (and approaches 1.00), strncpy will win, because it's copying 
loop is faster. The point of this discussion is that as long as Asterisk 
is using hundreds of fixed-length buffers that are never filled (or even 
50% filled), we are wasting a ton of CPU time (and probably cache/memory 
bus bandwidth) writing zeroes into memory with no purpose.



More information about the asterisk-dev mailing list