Skip to content

Instantly share code, notes, and snippets.

@levic
Created May 26, 2019 15:21
Show Gist options
  • Save levic/f4b61fe6defde03306dd48fd12728ab6 to your computer and use it in GitHub Desktop.
Save levic/f4b61fe6defde03306dd48fd12728ab6 to your computer and use it in GitHub Desktop.
C vs C++ startup cost
#include <stdlib.h>
#include <string.h>
const char* STR = "abcdefhijklm";
int main(int argc, char* argv[]) {
int x = strlen("abc");
void* v = malloc(100);
char* s = malloc(strlen(STR));
strcpy(s, STR);
return 0;
}
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <string>
const char* STR = "abcdefhijklm";
int main(int argc, char* argv[]) {
int x = strlen("abc");
void* v = malloc(100);
std::string s(STR);
return 0;
}
- ITERATIONS=15000
- OS: macOS 10.14.5
- Compiled using clang with -O3
Output:
running 15000 iterations for ./a.out.c
done
elapsed: 26.145948sec
1.743ms per iteration
running 15000 iterations for ./a.out.cpp
done
elapsed: 26.000413sec
1.733ms per iteration
#include <spawn.h>
#include <string.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#define ITERATIONS 1000
int spawnloop(const char* prog, char *envp[]) {
timeval start_time;
timeval end_time;
printf("running %d iterations for %s\n", ITERATIONS, prog);
gettimeofday(&start_time, NULL);
char* child_argv[] = {NULL};
for (int i = 0; i < ITERATIONS; i++) {
int err = -1;
pid_t child_pid = -1;
err = posix_spawn(
&child_pid,
prog,
NULL,
NULL,
child_argv,
envp
);
if (err != 0) {
printf("error %d (%s) @ iteration %d", err, strerror(err), i);
return 1;
}
int waitstatus;
waitpid(child_pid, &waitstatus, 0);
}
gettimeofday(&end_time, NULL);
printf("done\n");
timeval diff_time;
timersub(&end_time, &start_time, &diff_time);
double elapsed_usec = (diff_time.tv_sec*1000*1000 + diff_time.tv_usec);
printf("elapsed: %.6lfsec\n", elapsed_usec / 1000/1000);
double ms_per_iteration = elapsed_usec / (1000.0 * ITERATIONS);
printf("%.3lfms per iteration\n", ms_per_iteration);
printf("\n");
return 0;
}
int main(int argc, char* argv[], char* envp[]) {
int a = spawnloop("./a.out.c", envp);
sleep(3);
int b = spawnloop("./a.out.cpp", envp);
return a ? a : b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment