是否存在与Python的time.process_time()等效的C++实现?
Absolutely! Python's time.process_time() returns the total CPU time consumed by the current process (covering both user-mode and kernel-mode execution, and explicitly excluding time spent sleeping). C++ has direct equivalents, depending on your C++ version and target platform:
Starting with C++17, the standard library includes std::chrono::process_cpu_clock—this is the cleanest, most portable way to match Python's behavior. It's designed specifically to track the CPU time used by the entire process.
Here's a helper function you can use, plus how to integrate it into your loop:
#include <chrono> #include <iostream> // Helper function matching Python's time.process_time() behavior double process_time() { using namespace std::chrono; auto cpu_duration = process_cpu_clock::now().time_since_epoch(); return duration<double>(cpu_duration).count(); } int main() { int steps = 0; while (steps < 100) { // Your algorithm logic here steps++; // Print current process CPU time std::cout << "Current processing time: " << process_time() << " "; } std::cout << std::endl; return 0; }
If you're working with an older C++ standard, you'll need to use platform-native APIs to get process-level CPU time:
Linux/macOS/Unix-like Systems
Use clock_gettime() with the CLOCK_PROCESS_CPUTIME_ID flag, which returns the total CPU time for the entire process:
#include <time.h> #include <iostream> double process_time() { struct timespec ts; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); // Convert seconds + nanoseconds to total seconds return ts.tv_sec + static_cast<double>(ts.tv_nsec) / 1e9; }
Windows Systems
Use GetProcessTimes() to retrieve both kernel-mode and user-mode CPU time for the current process, then sum them:
#include <windows.h> #include <iostream> double process_time() { FILETIME create_time, exit_time, kernel_time, user_time; GetProcessTimes(GetCurrentProcess(), &create_time, &exit_time, &kernel_time, &user_time); // Convert FILETIME to 64-bit integers ULARGE_INTEGER kernel, user; kernel.LowPart = kernel_time.dwLowDateTime; kernel.HighPart = kernel_time.dwHighDateTime; user.LowPart = user_time.dwLowDateTime; user.HighPart = user_time.dwHighDateTime; // Convert total 100-nanosecond intervals to seconds return (kernel.QuadPart + user.QuadPart) / 1e7; }
- All these implementations match Python's
process_time()by only counting time the CPU was actively executing your process—time spent waiting (like sleep, I/O, or waiting for other processes) won't be included. - If you need to measure time elapsed between two points (instead of total process time since start), you can capture start/end time points and compute the difference (e.g.,
auto start = std::chrono::process_cpu_clock::now(); /* work */ auto elapsed = std::chrono::duration<double>(std::chrono::process_cpu_clock::now() - start).count();).
内容的提问来源于stack exchange,提问作者Wizard

