Skip to content

Instantly share code, notes, and snippets.

@nneonneo
Last active June 6, 2018 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nneonneo/f9dc5c1d1d342d25eae47d56dbad040e to your computer and use it in GitHub Desktop.
Save nneonneo/f9dc5c1d1d342d25eae47d56dbad040e to your computer and use it in GitHub Desktop.
strncpy speed test
#include <stdint.h>
#include <sys/time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
typedef uint64_t microclock_t;
static inline microclock_t microclock() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000ULL + tv.tv_usec;
}
int main(int argc, char **argv) {
if(argc < 2) {
fprintf(stderr, "Usage: %s <teststr>\n", argv[0]);
return 1;
}
char buffer[1024];
microclock_t start, end;
const int nloops = 10000000;
/* dummy accesses to warm up the cache */
for(int i=0; i<nloops; i++) {
memcpy(buffer, argv[1], strnlen(argv[1], sizeof(buffer)-1) + 1);
buffer[sizeof(buffer) - 1] = 0;
}
start = microclock();
for(int i=0; i<nloops; i++) {
memcpy(buffer, argv[1], strnlen(argv[1], sizeof(buffer)-1) + 1);
buffer[sizeof(buffer) - 1] = 0;
}
end = microclock();
printf("memcpy: %7"PRIu64" us\n", end - start);
#ifndef __linux__
start = microclock();
for(int i=0; i<nloops; i++) {
strlcpy(buffer, argv[1], sizeof(buffer));
}
end = microclock();
printf("strlcpy: %7"PRIu64" us\n", end - start);
#endif
start = microclock();
for(int i=0; i<nloops; i++) {
strncpy(buffer, argv[1], sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = 0;
}
end = microclock();
printf("strncpy: %7"PRIu64" us\n", end - start);
start = microclock();
for(int i=0; i<nloops; i++) {
sprintf(buffer, "%.*s", (int)sizeof(buffer)-1, argv[1]);
}
end = microclock();
printf("sprintf: %7"PRIu64" us\n", end - start);
start = microclock();
for(int i=0; i<nloops; i++) {
snprintf(buffer, sizeof(buffer), "%s", argv[1]);
}
end = microclock();
printf("snprintf: %7"PRIu64" us\n", end - start);
}
@nneonneo
Copy link
Author

nneonneo commented Jun 6, 2018

Results from a Linux box (16-byte string):

CPU: Xeon E5-2670 v3 @ 2.30GHz
command: cc -D_POSIX_C_SOURCE=201805 -std=c99 test.c -o test -O3
cc version: gcc (Ubuntu 4.8.4-2ubuntu1~14.04.4) 4.8.4

memcpy:    186443 us
strncpy:   485909 us
sprintf:   987185 us
snprintf:  935249 us

Results from a Mac:

CPU: Core i7 7820HQ @ 2.90GHz
command: cc test.c -o test -O3
cc version: Apple LLVM version 9.0.0 (clang-900.0.39.2)

memcpy:     76097 us
strlcpy:   102289 us
strncpy:   178519 us
sprintf:   754731 us
snprintf:  709304 us

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment