aboutsummaryrefslogtreecommitdiff
path: root/pal/windows.h
blob: 3a2a7cf5d1b790d148b8594637c48a2a807d3680 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#pragma once

#include <cassert>
#include <iostream>
#include <windows.h>
#include <psapi.h>

#define DECL_MAIN int __cdecl wmain()

#define NOINLINE __declspec(noinline)

namespace pal {

static constexpr size_t kPageSize = 0x1000;

inline void* MemReserve(size_t len) {
    void* buf = VirtualAlloc(nullptr, len, MEM_RESERVE, PAGE_NOACCESS);
    if (buf == nullptr) {
        DWORD last_error = GetLastError();
        std::cerr << "Reserving memory with VirtualAlloc failed. Error code: " << last_error << std::endl;
        return nullptr;
    }

    return buf;
}

inline bool MemCommit(void* p, size_t len) {
    void* committed = VirtualAlloc(p, len, MEM_COMMIT, PAGE_READWRITE);
    if (committed == nullptr) {
        DWORD last_error = GetLastError();
        std::cerr << "Committing memory with VirtualAlloc failed. Error code: " << last_error << std::endl;
        return false;
    }

    return true;
}

inline void MemFree(void* p, size_t /*len*/) {
    VirtualFree(p, 0, MEM_RELEASE);
}

inline size_t GetPeakMemoryUse() {
    PROCESS_MEMORY_COUNTERS mem;
    bool res = GetProcessMemoryInfo(GetCurrentProcess(), &mem, sizeof mem);
    if (!res) {
        DWORD last_error = GetLastError();
        std::cerr << "GetProcessMemoryInfo failed. Error code: " << last_error << std::endl;
        return 0;
    }

    return mem.PeakWorkingSetSize;
}

inline uint64_t ConvertFiletimeToMicroseconds(FILETIME t) {
    ULARGE_INTEGER li;
    li.LowPart = t.dwLowDateTime;
    li.HighPart = t.dwHighDateTime;
    return static_cast<uint64_t>(li.QuadPart) / 10;
}

inline uint64_t GetCpuTime() {
    FILETIME a, b, c, d;
    if (GetProcessTimes(GetCurrentProcess(), &a, &b, &c, &d) != 0) {
        auto kernel_time = ConvertFiletimeToMicroseconds(c);
        auto user_time = ConvertFiletimeToMicroseconds(d);
        return user_time + kernel_time;
    } else {
        std::cerr << "failed to get CPU time\n";
        assert(false);
        return 0;
    }
}

} // namespace pal