Created
August 6, 2014 23:15
-
-
Save bogen/1715b86f8a6f3269ff22 to your computer and use it in GitHub Desktop.
make line feed terminated string #2
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); | |
dst = (char*) malloc (len+2); | |
for (auto i = 0; i < 30000000; i++) { | |
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
$ time ./make_buffer c | |
2 | |
copy_append = 0x4007d0 | |
use_sprintf = 0x400810 | |
c | |
make_buffer = 0x4007d0 | |
real 0m0.925s | |
user 0m0.920s | |
sys 0m0.003s | |
$ time ./make_buffer s | |
2 | |
copy_append = 0x4007d0 | |
use_sprintf = 0x400810 | |
s | |
make_buffer = 0x400810 | |
real 0m8.799s | |
user 0m8.800s | |
sys 0m0.007s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment