Created
August 6, 2014 23:07
-
-
Save bogen/8804f820a6664671f9ce to your computer and use it in GitHub Desktop.
make line feed terminated string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
auto const src = "This is a test. This is a test. This is a test. This is a test."; | |
ssize_t len; | |
char* dst; | |
void copy_append () { | |
memcpy (dst, src, len); | |
dst [len] = '\n'; | |
} | |
void use_sprintf () { sprintf (dst, "%s\n", src); } | |
int main (int argc, char **argv) { | |
printf ("%d\n", argc); | |
if (argc < 2) return 1; | |
auto make_buffer = copy_append; | |
printf ("copy_append = %p\n", copy_append); | |
printf ("use_sprintf = %p\n", use_sprintf); | |
printf ("%c\n", argv [1][0]); | |
switch (argv [1][0]) { | |
case 's': make_buffer = use_sprintf; break; | |
case 'c': break; | |
default: return 2; | |
} | |
printf ("make_buffer = %p\n", make_buffer); | |
len = strlen (src); | |
for (auto i = 0; i < 30000000; i++) { | |
dst = (char*) malloc (len+2); | |
make_buffer (); | |
free (dst); | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ g++ -std=c++11 -O2 -o make_buffer make_buffer.c | |
#using sprintf | |
$ time ./make_buffer s | |
2 | |
copy_append = 0x4007d0 | |
use_sprintf = 0x400810 | |
s | |
make_buffer = 0x400810 | |
real 0m11.506s | |
user 0m11.510s | |
sys 0m0.003s | |
#using copy/append | |
$ time ./make_buffer c | |
2 | |
copy_append = 0x4007d0 | |
use_sprintf = 0x400810 | |
c | |
make_buffer = 0x4007d0 | |
real 0m3.488s | |
user 0m3.483s | |
sys 0m0.000s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment