Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <assert.h>
- #include <dlfcn.h>
- #include <limits.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/time.h>
- #define SETSIZE 10
- #define NRUNS 10000000
- typedef int (*func)(uint32_t);
- static func
- getfunc(uint32_t *set)
- {
- size_t i;
- FILE *f;
- char path[PATH_MAX];
- char *pres;
- void *dlhandle;
- func r;
- char *error;
- f = fopen("dcode.c", "w");
- assert(f != NULL);
- fprintf(f, "#include <stdint.h>\n\n");
- fprintf(f, "int set_test(uint32_t key) {\n");
- for (i=0; i<SETSIZE; i++) {
- fprintf(f, " if (key == %d) return 1;\n", set[i]);
- }
- fprintf(f, " return 0;\n}\n");
- fclose(f);
- system("cc -s -O3 -c dcode.c");
- system("cc -shared -Wl,-soname,libdcst.so -o libdcst.so dcode.o");
- pres = realpath("libdcst.so", path);
- assert(pres != NULL);
- dlhandle = dlopen(path, RTLD_NOW);
- assert(dlhandle != NULL);
- *(void **) &r = dlsym(dlhandle, "set_test");
- if ((error = dlerror()) != NULL) {
- fprintf(stderr, "%s\n", error);
- exit(EXIT_FAILURE);
- }
- /* dlclose(dlhandle);*/
- return r;
- }
- int
- main()
- {
- uint32_t set[SETSIZE];
- size_t i;
- func f;
- struct timeval begin, end;
- int acc;
- for (i=0; i<SETSIZE; i++) {
- set[i] = rand();
- }
- f = getfunc(set);
- gettimeofday(&begin, NULL);
- acc = 0;
- for (i=0; i<NRUNS; i++) {
- uint32_t sample;
- sample = rand();
- if (f(sample)) acc++;
- }
- gettimeofday(&end, NULL);
- printf("direct code: %f secs\n", ((double)((end.tv_sec - begin.tv_sec)*1000000 + end.tv_usec - begin.tv_usec)) / 1000000.0);
- acc = 0;
- gettimeofday(&begin, NULL);
- for (i=0; i<NRUNS; i++) {
- uint32_t sample;
- int j;
- sample = rand();
- for (j=0; j<SETSIZE; j++) {
- if (set[j] == sample) acc++;
- }
- }
- gettimeofday(&end, NULL);
- printf("linear search: %f secs, acc=%d\n", ((double)((end.tv_sec - begin.tv_sec)*1000000 + end.tv_usec - begin.tv_usec)) / 1000000.0, acc);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment