程序时空
时间
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;
}
本文作者:XuYueming,转载请注明原文链接:https://www.cnblogs.com/XuYueming/p/19073562。
若未作特殊说明,本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可。