- Make get_total_memory work for windows
- Add test cases for it
This commit is contained in:
parent
61cad69671
commit
1126d7bd10
@ -1,27 +1,58 @@
|
||||
#include "get_total_memory.h"
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#if defined(__APPLE__)
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/sysctl.h>
|
||||
#include <unistd.h>
|
||||
#include <stdexcept>
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#elif defined(__linux__) || defined(__FreeBSD__)
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
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 <Windows.h>
|
||||
|
||||
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
|
||||
|
||||
|
@ -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
|
||||
|
13
test/cpp-utils/system/GetTotalMemoryTest.cpp
Normal file
13
test/cpp-utils/system/GetTotalMemoryTest.cpp
Normal file
@ -0,0 +1,13 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <cpp-utils/system/get_total_memory.h>
|
||||
|
||||
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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user