Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <assert.h>
- #include <time.h>
- #include <lua.h>
- #include <lauxlib.h>
- #include <lualib.h>
- double
- gettime(void)
- {
- struct timespec ts;
- if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) {
- perror("clock_getres");
- exit(EXIT_FAILURE);
- }
- return ts.tv_sec + 1e-9 * ts.tv_nsec;
- }
- void
- bench_forks(int nspawns, char *const *args)
- {
- double timer = gettime();
- for (int i = 0; i < nspawns; ++i) {
- pid_t pid = fork();
- if (pid < 0) {
- perror("fork");
- exit(EXIT_FAILURE);
- } else if (pid == 0) {
- execvp(args[0], args);
- perror("execvp");
- exit(127);
- } else {
- int status;
- if (waitpid(pid, &status, 0) < 0) {
- perror("waitpid");
- exit(EXIT_FAILURE);
- }
- if (!WIFEXITED(status)) {
- fprintf(stderr, "child process terminated in an abnormal way\n");
- exit(EXIT_FAILURE);
- }
- if (WEXITSTATUS(status) != 0) {
- fprintf(stderr, "child process exited with non-zero exit code %d\n",
- WEXITSTATUS(status));
- exit(EXIT_FAILURE);
- }
- }
- }
- timer = gettime() - timer;
- printf("%d spawns in %.2lf seconds: %.2lf forks per second\n", nspawns, timer, nspawns / timer);
- }
- void
- check_lua_call(lua_State *L, int retval)
- {
- if (retval == 0) {
- return;
- }
- const char *msg = lua_tostring(L, -1);
- fprintf(stderr, "Lua error: %s\n", msg ? msg : "(error object can't be converted to string)");
- exit(EXIT_FAILURE);
- }
- void
- bench_lua(int ncalls, const char *filename, const char *func, const char *arg)
- {
- lua_State *L = luaL_newstate();
- assert(L); // L: -
- luaL_openlibs(L); // L: -
- check_lua_call(L, luaL_dofile(L, filename)); // L: -
- #if LUA_VERSION_NUM >= 502
- lua_pushglobaltable(L);
- #else
- lua_pushvalue(L, LUA_GLOBALSINDEX);
- #endif
- // L: _G
- double timer = gettime();
- lua_getfield(L, -1, func); // L: _G func
- int ref = luaL_ref(L, LUA_REGISTRYINDEX); // L: _G
- lua_pop(L, 1); // L: -
- for (int i = 0; i < ncalls; ++i) {
- lua_rawgeti(L, LUA_REGISTRYINDEX, ref); // L: func
- lua_pushstring(L, arg); // L: func arg
- check_lua_call(L, lua_pcall(L, 1, 0, 0)); // L: -
- }
- timer = gettime() - timer;
- printf("%d calls in %.2lf seconds: %.2lf calls per second\n", ncalls, timer, ncalls / timer);
- lua_close(L);
- }
- int
- main()
- {
- bench_forks(1000, (char *const[]) {"./my_true", NULL});
- bench_lua(1000, "./file.lua", "my_func", "hello");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement