protoverse

A metaverse protocol
git clone git://jb55.com/protoverse
Log | Files | Refs | README | LICENSE

bench.c (1771B)


      1 #include <time.h>
      2 #include <stdlib.h>
      3 #include <assert.h>
      4 #include <sys/mman.h>
      5 
      6 #include "io.h"
      7 #include "wasm.h"
      8 
      9 static int bench_wasm(unsigned char *wasm, unsigned long len, int times,
     10 		int argc, const char **argv, char **env)
     11 {
     12 	struct wasm_parser p;
     13 	struct wasm_interp interp;
     14 	struct timespec t1, t2;
     15 	int i, ops = 0;
     16 	int retval;
     17 	long nanos, ms;
     18 
     19 	wasm_parser_init(&p, wasm, len, len*16, 0, 0);
     20 
     21 	if (!parse_wasm(&p)) {
     22 		return 0;
     23 	}
     24 
     25 	if (!wasm_interp_init(&interp, &p.module)) {
     26 		print_error_backtrace(&interp.errors);
     27 		return 0;
     28 	}
     29 	interp.errors.enabled = 0;
     30 
     31 	setup_wasi(&interp, argc, argv, env);
     32 
     33 	clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t1);
     34 	for (i = 0; i < times; i++) {
     35 		if (!interp_wasm_module(&interp, &retval)) {
     36 			print_error_backtrace(&interp.errors);
     37 		}
     38 		ops += interp.ops;
     39 	}
     40 	clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t2);
     41 
     42 	nanos = (t2.tv_sec - t1.tv_sec) * (long)1e9 + (t2.tv_nsec - t1.tv_nsec);
     43 	ms = nanos / 1e6;
     44 	printf("ns/run\t%ld\nms/run\t%f\nns\t%ld\nms\t%ld\nops\t%d\nns/op\t%ld\n",
     45 		nanos/times, (double)ms/(double)times, nanos, ms, ops, nanos/(ops+1));
     46 
     47 	wasm_interp_free(&interp);
     48 	wasm_parser_free(&p);
     49 	return 1;
     50 }
     51 
     52 int main(int argc, char *argv[], char **env)
     53 {
     54 	unsigned char *wasm_data;
     55 	const char *code_file;
     56 	size_t len;
     57 	int times;
     58 	int args = 0;
     59 
     60 	if (argc >= 2) {
     61 		args++;
     62 		code_file = argv[1];
     63 	}
     64 	else
     65 		code_file = "wasm/hello.wasm";
     66 
     67 	if (argc >= 3) {
     68 		args++;
     69 		times = atoi(argv[2]);
     70 	}
     71 	else
     72 		times = 10000;
     73 
     74 	if (!map_file(code_file, &wasm_data, &len)) {
     75 		perror("mmap");
     76 		return 1;
     77 	}
     78 	fprintf(stderr, "executing %s %d times\n", code_file, times);
     79 	if (!bench_wasm(wasm_data, len, times, argc-args,
     80 				((const char**)argv)+args, env)) {
     81 		return 2;
     82 	}
     83 
     84 	munmap(wasm_data, len);
     85 
     86 	return 0;
     87 }
     88