Log approximate RAM usage of mods during startup (with --info)

master
luk3yx 2021-09-13 19:50:04 +12:00 committed by MoNTE48
parent 5d1b891c6b
commit a3e3f12900
4 changed files with 40 additions and 1 deletions

View File

@ -441,6 +441,7 @@ void set_default_settings()
settings->setDefault("emergequeue_limit_diskonly", "128");
settings->setDefault("emergequeue_limit_generate", "128");
settings->setDefault("num_emerge_threads", "1");
settings->setDefault("log_mod_memory_usage_on_load", "false");
settings->setDefault("secure.enable_security", "true");
settings->setDefault("secure.trusted_mods", "");
settings->setDefault("secure.http_mods", "");

View File

@ -196,3 +196,19 @@ std::string ScriptApiServer::formatChatMessage(const std::string &name,
return ret;
}
size_t ScriptApiServer::getMemoryUsageKB() {
lua_State *L = getStack();
// Call collectgarbage() to try and improve the accuracy
lua_getglobal(L, "collectgarbage");
lua_call(L, 0, 0);
// Call collectgarbage("count") to obtain the memory usage
lua_getglobal(L, "collectgarbage");
lua_pushstring(L, "count");
lua_call(L, 1, 1);
double memory_usage_kb = lua_tonumber(L, -1);
lua_pop(L, 1);
return memory_usage_kb;
}

View File

@ -49,6 +49,9 @@ public:
const std::string &password);
bool setPassword(const std::string &playername,
const std::string &password);
// Note that this calls collectgarbage() first.
size_t getMemoryUsageKB();
private:
void getAuthHandler();
void readPrivileges(int index, std::set<std::string> &result);

View File

@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "scripting_server.h"
#include "content/subgames.h"
#include "porting.h"
#include "settings.h"
#include "util/metricsbackend.h"
/**
@ -59,6 +60,9 @@ void ServerModManager::loadMods(ServerScripting *script)
infostream << mod.name << " ";
}
infostream << std::endl;
const bool log_mem = g_settings->getBool("log_mod_memory_usage_on_load");
// Load and run "mod" scripts
for (const ModSpec &mod : m_sorted_mods) {
if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
@ -69,7 +73,22 @@ void ServerModManager::loadMods(ServerScripting *script)
}
std::string script_path = mod.path + DIR_DELIM + "init.lua";
auto t = porting::getTimeMs();
script->loadMod(script_path, mod.name);
// This is behind a setting since getMemoryUsageKB calls
// collectgarbage() first which will slow down load times.
if (log_mem) {
size_t old_usage = script->getMemoryUsageKB();
script->loadMod(script_path, mod.name);
size_t new_usage = script->getMemoryUsageKB();
actionstream << "Mod \"" << mod.name << "\" loaded, ";
if (new_usage >= old_usage)
actionstream << "using " << (new_usage - old_usage);
else
actionstream << "somehow freeing " << (old_usage - new_usage);
actionstream << "KB of memory" << std::endl;
} else {
script->loadMod(script_path, mod.name);
}
infostream << "Mod \"" << mod.name << "\" loaded after "
<< (porting::getTimeMs() - t) << " ms" << std::endl;
}