Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #include <stdint.h>
- #define IMAX 262144
- #define PAGE_SIZE 4096
- static size_t bump_size(char ** buffer, size_t existing, size_t additional) {
- size_t desired;
- size_t ideal;
- if (existing + additional > (existing << 1)) {
- desired = existing + additional;
- } else {
- desired = existing << 1;
- }
- ideal = ((desired + PAGE_SIZE) >> 12) << 12;
- if (!((*buffer) = realloc(*buffer, ideal))) {
- perror("Error increasing memory allocation. Aborting.");
- exit(EXIT_FAILURE);
- }
- return ideal;
- }
- int main() {
- setbuf(stdout, NULL); //disable output buffering
- /* this is known at compile time, why not:
- * const char str[] = "abcdefghefghefgh";
- * ? Still, won't "cheat"... */
- /* stupid unneeded mess */
- size_t str_mem = 9;
- char * str = malloc(str_mem);
- if(str == NULL) {
- perror("Failed to allocate initial memory for str.");
- return EXIT_FAILURE;
- }
- (void) strcpy(str, "abcdefgh");
- /* not worth optimizing, since it's not in the loop, but could
- * also, wouldn't really use bump_size here, just raw realloc
- * but I am to demonstrate this is a viable general technique */
- str_mem = bump_size(&str, str_mem, 8);
- strcat(str, "efghefgh");
- /* end stupid unneeded mess that should have been statically declared */
- printf("%s", "exec.tm.sec\tstr.length\n");
- time_t starttime = time(NULL);
- char * gstr = malloc(1);
- if (!gstr) {
- perror("Error allocating memory for gstr. Exiting.");
- return EXIT_FAILURE;
- }
- gstr[0] = '\0';
- size_t gstr_len = 0;
- size_t gstr_size = 1;
- char * pos_c = gstr;
- size_t str_len = strlen(str);
- size_t str_size = str_len + 1;
- size_t efgh_len = strlen("efgh"); // 4. To keep it general and avoid magic constants
- size_t i = 0;
- while (i++ < IMAX+1000) {
- if ((gstr_len + str_size) > gstr_size) {
- gstr_size = bump_size(&gstr, gstr_size, str_len);
- }
- pos_c = gstr + gstr_len;
- memcpy(pos_c, str, str_size); //strcat(gstr, str);
- gstr_len += str_len;
- while((pos_c = strnstr(pos_c, "efgh", str_len))) {
- memcpy(pos_c, "____", efgh_len);
- pos_c += efgh_len;
- }
- if (gstr_len % IMAX == 0) {
- printf("%ldsec\t\t%lukb\n", time(NULL) - starttime, gstr_len / 1024);
- }
- }
- //printf("%s\n",gstr);
- free(gstr);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement