diff --git a/src/cpp-utils/system/get_total_memory.cpp b/src/cpp-utils/system/get_total_memory.cpp index 83abe6cd..85f197c7 100644 --- a/src/cpp-utils/system/get_total_memory.cpp +++ b/src/cpp-utils/system/get_total_memory.cpp @@ -1,27 +1,58 @@ #include "get_total_memory.h" +#include +#include + +#if defined(__APPLE__) + #include #include -#include -#include -namespace cpputils{ - namespace system { - uint64_t get_total_memory() { - uint64_t mem; -#if defined(__APPLE__) - size_t size = sizeof(mem); - int result = sysctlbyname("hw.memsize", &mem, &size, nullptr, 0); - if (0 != result) { - throw std::runtime_error("sysctlbyname syscall failed"); - } -#elif defined(__linux__) || defined(__FreeBSD__) - long numRAMPages = sysconf(_SC_PHYS_PAGES); - long pageSize = sysconf(_SC_PAGESIZE); - mem = numRAMPages * pageSize; -#else -#error Not supported on windows yet, TODO http://stackoverflow.com/a/2513561/829568 -#endif - return mem; - } - } +namespace cpputils { + namespace system { + uint64_t get_total_memory() { + uint64_t mem; + size_t size = sizeof(mem); + int result = sysctlbyname("hw.memsize", &mem, &size, nullptr, 0); + if (0 != result) { + throw std::runtime_error("sysctlbyname syscall failed"); + } + return mem; + } + } } + +#elif defined(__linux__) || defined(__FreeBSD__) + +#include + +namespace cpputils { + namespace system { + uint64_t get_total_memory() { + long numRAMPages = sysconf(_SC_PHYS_PAGES); + long pageSize = sysconf(_SC_PAGESIZE); + return numRAMPages * pageSize; + } + } +} + +#elif defined(_MSC_VER) + +#include + +namespace cpputils { + namespace system { + uint64_t get_total_memory() { + MEMORYSTATUSEX status; + status.dwLength = sizeof(status); + if (!::GlobalMemoryStatusEx(&status)) { + throw std::runtime_error("Couldn't get system memory information. Error code: " + std::to_string(GetLastError())); + } + return status.ullTotalPhys; + } + } +} + +#else +#error Unsupported platform +#endif + diff --git a/test/cpp-utils/CMakeLists.txt b/test/cpp-utils/CMakeLists.txt index 9d5023c8..7fac4757 100644 --- a/test/cpp-utils/CMakeLists.txt +++ b/test/cpp-utils/CMakeLists.txt @@ -45,6 +45,7 @@ set(SOURCES assert/backtrace_include_test.cpp assert/assert_include_test.cpp assert/assert_debug_test.cpp + system/GetTotalMemoryTest.cpp system/TimeTest.cpp system/MemoryTest.cpp system/HomedirTest.cpp diff --git a/test/cpp-utils/system/GetTotalMemoryTest.cpp b/test/cpp-utils/system/GetTotalMemoryTest.cpp new file mode 100644 index 00000000..81c57f48 --- /dev/null +++ b/test/cpp-utils/system/GetTotalMemoryTest.cpp @@ -0,0 +1,13 @@ +#include +#include + +using cpputils::system::get_total_memory; + +TEST(GetTotalMemoryTest, DoesntCrash) { + get_total_memory(); +} + +TEST(GetTotalMemoryTest, IsNotZero) { + uint64_t mem = get_total_memory(); + EXPECT_LT(UINT64_C(0), mem); +}