Advertisement
somya-kr

incremental-gc

Aug 18th, 2024 (edited)
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #include <lua.h>
  2. #include <lauxlib.h>
  3. #include <lualib.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6.  
  7. void bail(lua_State *L, const char *msg) {
  8. fprintf(stderr, "\nFATAL ERROR:\n %s: %s\n\n", msg, lua_tostring(L, -1));
  9. lua_close(L);
  10. exit(1);
  11. }
  12.  
  13. void print_gc_stats(lua_State *L, const char *msg) {
  14. int kb_in_use = lua_gc(L, LUA_GCCOUNT, 0);
  15. int kb_in_use_rem = lua_gc(L, LUA_GCCOUNTB, 0);
  16.  
  17. printf("GC Stats (%s):\n", msg);
  18. for(int i = 0; i < 40; i++) {
  19. printf("-");
  20. }
  21. printf("\n");
  22. printf("Total memory in use: %d.%d KB\n", kb_in_use, kb_in_use_rem);
  23. printf("\n\n");
  24. }
  25.  
  26.  
  27. int main(void) {
  28. lua_State *L;
  29.  
  30. L = luaL_newstate();
  31. luaL_openlibs(L);
  32.  
  33.  
  34. lua_gc(L, LUA_GCSETPAUSE, 150);
  35. lua_gc(L, LUA_GCSETSTEPMUL, 500);
  36.  
  37.  
  38. if (luaL_loadfile(L, "testbench.lua"))
  39. bail(L, "luaL_loadfile() failed");
  40.  
  41. printf("In C, calling Lua with incremental GC\n\n");
  42.  
  43. print_gc_stats(L, "Before running script");
  44.  
  45. if (lua_pcall(L, 0, 0, 0))
  46. bail(L, "lua_pcall() failed");
  47.  
  48. lua_getglobal(L, "test");
  49.  
  50. if (lua_pcall(L, 0, 0, 0))
  51. bail(L, "lua_pcall() failed");
  52.  
  53. print_gc_stats(L, "After running test function");
  54.  
  55. // The GC does not work if we do not manually call the incremental steps below
  56. for(int i = 0; i < 2; i++) {
  57. lua_gc(L, LUA_GCSTEP, 0);
  58. }
  59.  
  60. print_gc_stats(L, "After incremental GC cycle");
  61. lua_close(L);
  62.  
  63. return 0;
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement