benchmark.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <iostream>
  2. #include <ctime>
  3. namespace std
  4. {
  5. using ::clock_t;
  6. // using ::clock;
  7. }
  8. #define LUABIND_NO_ERROR_CHECKING
  9. #define LUABIND_DONT_COPY_STRINGS
  10. //#define LUABIND_NOT_THREADSAFE
  11. extern "C"
  12. {
  13. #include "lua.h"
  14. #include "lauxlib.h"
  15. }
  16. #include <luabind/luabind.hpp>
  17. struct A {};
  18. // luabind function
  19. float f1(int a, float b, const char* str, A* c)
  20. {
  21. return 3.14f;
  22. }
  23. // empty function
  24. int f2(lua_State* L)
  25. {
  26. return 0;
  27. }
  28. int main()
  29. {
  30. const int num_calls = 100000;
  31. const int loops = 10;
  32. using namespace luabind;
  33. lua_State* L = lua_open();
  34. open(L);
  35. class_<A>(L, "A")
  36. .def(constructor<>());
  37. function(L, "test1", &f1);
  38. lua_pushstring(L, "test2");
  39. lua_pushcclosure(L, &f2, 0);
  40. lua_settable(L, LUA_GLOBALSINDEX);
  41. std::clock_t total1 = 0;
  42. std::clock_t total2 = 0;
  43. for (int i = 0; i < loops; ++i)
  44. {
  45. // benchmark luabind
  46. std::clock_t start1 = std::clock();
  47. lua_dostring(L, "a = A()\n"
  48. "for i = 1, 100000 do\n"
  49. "test1(5, 4.6, 'foo', a)\n"
  50. "end");
  51. std::clock_t end1 = std::clock();
  52. // benchmark empty binding
  53. std::clock_t start2 = std::clock();
  54. lua_dostring(L, "a = A()\n"
  55. "for i = 1, 100000 do\n"
  56. "test2(5, 4.6, 'foo', a)\n"
  57. "end");
  58. std::clock_t end2 = std::clock();
  59. total1 += end1 - start1;
  60. total2 += end2 - start2;
  61. }
  62. double time1 = double(total1) / (double)CLOCKS_PER_SEC;
  63. double time2 = double(total2) / (double)CLOCKS_PER_SEC;
  64. #ifdef LUABIND_NO_ERROR_CHECKING
  65. std::cout << "without error-checking\n";
  66. #endif
  67. std::cout << "luabind:\t" << time1 * 1000000 / num_calls / loops << " microseconds per call\n"
  68. << "empty:\t" << time2 * 1000000 / num_calls / loops << " microseconds per call\n"
  69. << "diff:\t" << ((time1 - time2) * 1000000 / num_calls / loops) << " microseconds\n\n";
  70. lua_close(L);
  71. }