Created
February 25, 2019 14:30
-
-
Save afcidk/441abae865be13c599b8f749792908b6 to your computer and use it in GitHub Desktop.
Simple code for checking the speed difference between function call and macro
This file contains hidden or 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> | |
| #include <sys/time.h> | |
| #ifdef MACRO | |
| #define func(a,b) a*b | |
| #else | |
| int func(int a, int b) { | |
| return a*b; | |
| } | |
| #endif | |
| long long getLong(char *s) { | |
| long long ret = 0; | |
| int len = strlen(s); | |
| for (int i=0; i<len; ++i) { | |
| ret *= 10; | |
| ret += s[i]-'0'; | |
| } | |
| return ret; | |
| } | |
| int main(int argc, char **argv) { | |
| int ret; | |
| if (argc <= 1) exit(0); | |
| long long cnt = getLong(argv[1]); | |
| FILE *f = fopen(NAME, "w"); | |
| for (long long i=0; i<cnt; ++i) { | |
| printf("recording %lld\n", i); | |
| long long tmp = i; | |
| struct timeval start, end, diff; | |
| gettimeofday(&start, NULL); | |
| while (tmp--) { | |
| ret = func(1, 1); | |
| } | |
| gettimeofday(&end, NULL); | |
| diff.tv_sec = end.tv_sec - start.tv_sec; | |
| diff.tv_usec = end.tv_usec + (1000000 - start.tv_usec); | |
| if (diff.tv_usec < 1000000) --diff.tv_sec; | |
| else diff.tv_usec -= 1000000; | |
| fprintf(f, "%lld %lf\n", i, diff.tv_sec+1e-6*diff.tv_usec); | |
| } | |
| return 0; | |
| } |
This file contains hidden or 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
| CC = gcc | |
| SIZE = 100000 | |
| all: macro function | |
| macro: base.c | |
| $(CC) -o macro base.c -DMACRO -g -DNAME=\"macro.log\" | |
| function: base.c | |
| $(CC) -o function base.c -g -DNAME=\"func.log\" | |
| test: macro function | |
| ./macro $(SIZE) | |
| ./function $(SIZE) | |
| plot: test | |
| gnuplot plot.gp | |
| clean: | |
| rm *.log macro function runtime.png |
This file contains hidden or 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
| # Load the files | |
| set term png enhanced font 'Verdana,10' | |
| set output 'runtime.png' | |
| set xlabel 'number of iterations' | |
| set ylabel 'time (s)' | |
| set logscale x | |
| plot [:][:]'macro.log' using 1:2 with points title 'macro',\ | |
| 'func.log' using 1:2 with points title 'function' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment