Created
March 30, 2015 10:41
-
-
Save flaviodesousa/6845950f6762d45d86f5 to your computer and use it in GitHub Desktop.
Exploring the time complexity of strcat() and realloc()
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 <string.h> | |
#include <stdlib.h> | |
#include <time.h> | |
void measure(char *name, void (*func)(char**,char *,char*,int), char **target, char *initial, char *repeat, int times) | |
{ | |
clock_t start, finish; | |
start = clock(); | |
func(target, initial, repeat, times); | |
free(*target); | |
finish = clock(); | |
printf("%20s: %10lld\n", name, (long long)(finish - start)); | |
} | |
void realloc_catter(char **target, char *initial, char *repeat, int times) | |
{ | |
*target = malloc(strlen(initial)+1); | |
strcpy(*target, initial); | |
for (int i = 0; i < times; i++) { | |
*target = realloc(*target, strlen(*target) + strlen(repeat) + 1); | |
strcat(*target, repeat); | |
} | |
} | |
void prealloc_catter(char **target, char *initial, char *repeat, int times) | |
{ | |
*target = malloc(strlen(initial) + strlen(repeat) * times + 1); | |
strcpy(*target, initial); | |
for (int i = 0; i < times; i++) { | |
strcat(*target, repeat); | |
} | |
} | |
char *mystrcat(char *target, char *repeat) | |
{ | |
for(;;) { | |
*target = *repeat; | |
if (!*repeat) break; | |
target++; | |
repeat++; | |
} | |
return target; | |
} | |
void realloc_mycatter(char **target, char *initial, char *repeat, int times) | |
{ | |
char *catptr = *target = malloc(strlen(initial)+1); | |
strcpy(*target, initial); | |
for (int i = 0; i < times; i++) { | |
*target = realloc(*target, strlen(*target) + strlen(repeat) + 1); | |
catptr = mystrcat(catptr, repeat); | |
} | |
} | |
void prealloc_mycatter(char **target, char *initial, char *repeat, int times) | |
{ | |
char *catptr = *target = malloc(strlen(initial) + strlen(repeat) * times + 1); | |
strcpy(*target, initial); | |
for (int i = 0; i < times; i++) { | |
catptr = mystrcat(catptr, repeat); | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
if (argc < 4) exit(1); | |
char *initial = argv[1]; | |
char *repeat = argv[2]; | |
int times = atoi(argv[3]); | |
char *target; | |
measure("realloc_catter", realloc_catter, &target, initial, repeat, times); | |
measure("prealloc_catter", prealloc_catter, &target, initial, repeat, times); | |
measure("realloc_mycatter", realloc_mycatter, &target, initial, repeat, times); | |
measure("prealloc_mycatter", prealloc_mycatter, &target, initial, repeat, times); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment