Skip to content

Commit

Permalink
Vary lua GC frequency based on load
Browse files Browse the repository at this point in the history
  • Loading branch information
ashdnazg committed May 5, 2018
1 parent 8968003 commit 0e61b6f
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
3 changes: 3 additions & 0 deletions rts/Lua/LuaAllocState.h
Expand Up @@ -4,11 +4,14 @@
#include <atomic>

struct SLuaAllocState {
static constexpr uint32_t maxAllocedBytes = 768u * (1024u * 1024u);
std::atomic<uint64_t> allocedBytes;
std::atomic<uint64_t> numLuaAllocs;
std::atomic<uint64_t> luaAllocTime;
std::atomic<uint64_t> numLuaStates;
};

extern SLuaAllocState gLuaAllocState;

#endif

4 changes: 4 additions & 0 deletions rts/Lua/LuaHandle.cpp
Expand Up @@ -2474,6 +2474,10 @@ CONFIG(float, LuaGarbageCollectionTimeMult).defaultValue(5.0f).minimumValue(1.0f

void CLuaHandle::CollectGarbage()
{
// if memory load is smaller than 75% run the GC less frequently
if (guRNG.NextFloat() > (1.33f * float(gLuaAllocState.allocedBytes.load()) / float(SLuaAllocState::maxAllocedBytes)))
return;

lua_lock(L_GC);
SetHandleRunning(L_GC, true);

Expand Down
7 changes: 3 additions & 4 deletions rts/lib/lua/include/LuaUser.cpp
Expand Up @@ -177,11 +177,10 @@ const char* spring_lua_get_handle_name(lua_State* L)
///////////////////////////////////////////////////////////////////////////
// Custom Memory Allocator
//
static constexpr uint32_t maxAllocedBytes = 768u * (1024u * 1024u);
static constexpr const char* maxAllocFmtStr = "[%s][handle=%s][OOM] synced=%d {alloced,maximum}={%u,%u}bytes\n";

// tracks allocations across all states
static SLuaAllocState gLuaAllocState = {{0}, {0}, {0}, {0}};
SLuaAllocState gLuaAllocState = {{0}, {0}, {0}, {0}};
static SLuaAllocError gLuaAllocError = {};

void spring_lua_alloc_log_error(const luaContextData* lcd)
Expand All @@ -198,7 +197,7 @@ void spring_lua_alloc_log_error(const luaContextData* lcd)
e.msgPtr = &e.msgBuf[0];

// append to buffer until it fills up or get_error is called
e.msgPtr += SNPRINTF(e.msgPtr, sizeof(e.msgBuf) - (e.msgPtr - &e.msgBuf[0]), fmt, __func__, lhn, lcd->synced, uint32_t(s.allocedBytes), maxAllocedBytes);
e.msgPtr += SNPRINTF(e.msgPtr, sizeof(e.msgBuf) - (e.msgPtr - &e.msgBuf[0]), fmt, __func__, lhn, lcd->synced, uint32_t(s.allocedBytes), SLuaAllocState::maxAllocedBytes);
}

void* spring_lua_alloc(void* ud, void* ptr, size_t osize, size_t nsize)
Expand All @@ -218,7 +217,7 @@ void* spring_lua_alloc(void* ud, void* ptr, size_t osize, size_t nsize)
return nullptr;
}

if ((nsize > osize) && (gLuaAllocState.allocedBytes.load() > maxAllocedBytes)) {
if ((nsize > osize) && (gLuaAllocState.allocedBytes.load() > SLuaAllocState::maxAllocedBytes)) {
// (re)allocation
// better kill Lua than whole engine; instant desync if synced handle
// NOTE: this will trigger luaD_throw, which calls exit(EXIT_FAILURE)
Expand Down

0 comments on commit 0e61b6f

Please sign in to comment.