程序时空

时间

Windows

chrono

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

int main() {
    auto start = chrono::steady_clock::now();
    {
        volatile int n = 1e9;
        volatile long long sum = 0;
        for (int i = 1; i <= n; ++i) {
            sum += i;
        }
        printf("%lld\n", sum);
    }
    auto end = chrono::steady_clock::now();
    auto elapsed = chrono::duration_cast<chrono::milliseconds>(end - start);
    cout << "耗时: " << elapsed.count() << " ms\n";
}

Linux

也可以用 chrono,或者用命令行:

/usr/bin/time -v ./prog

空间

Windows

用 Windows 提供的 API。统计程序峰值内存,包括栈空间。

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

int main() {
    PROCESS_MEMORY_COUNTERS pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
    std::cout << "峰值内存: " << pmc.PeakWorkingSetSize / 1024 / 1024 << " MB\n";
}

注意提交的时候不要忘记注释掉。一些情况下需要手动添加链接 psapi 命令。

g++ prog.cpp -o prog.exe -O2 -std=c++14 -lpsapi

Linux

#include <fstream>
#include <string>
#include <iostream>

size_t getPeakMemoryKB() {
    std::ifstream status("/proc/self/status");
    std::string line;
    while (std::getline(status, line)) {
        if (line.substr(0, 5) == "VmHWM") {
            size_t kb = 0;
            sscanf(line.c_str(), "VmHWM: %zu kB", &kb);
            return kb;
        }
    }
    return 0;
}
posted @ 2025-09-04 15:23  XuYueming  阅读(17)  评论(0)    收藏  举报