测量Windows C ++的时间,毫秒或微秒 [英] Measure time, milliseconds or microseconds for Windows C++
问题描述
如何在Windows C ++中测量执行时间(以毫秒或微秒为单位)?
How do you measure the execution time in milliseconds or microseconds in Windows C++?
我发现很多方法一个调用时间
I found many method one calling time(NULL), but it measures time in seconds only and the seconds clock() (clock_t) measure CPU time, not the actual time.
我发现本文中提到的函数gettimeofday(日历时间):
dropbox.com/s/k0zv8pck7ydbakz/1_7-PDF_thesis_2.pdf
I found the function gettimeofday(Calendar time) mentioned in this paper: dropbox.com/s/k0zv8pck7ydbakz/1_7-PDF_thesis_2.pdf
此函数适用于Linux(计算时间单位为毫秒和微秒),而不是Windows。
This function is for Linux (compute time in milli and microseconds) and not Windows.
我找到了Windows的替代方法:
dropbox.com/s/ofo99b166l7e2gf/gettimeofday.txt
I found an alternative to it for Windows: dropbox.com/s/ofo99b166l7e2gf/gettimeofday.txt
这可能是相关的:stackoverflow.com/questions/1861294/how-to-calculate-execution-time-of-a-code-snippet-in-c
And this may be relevant: stackoverflow.com/questions/1861294/how-to-calculate-execution-time-of-a-code-snippet-in-c
推荐答案
您可以使用标准C ++ < chrono>
图书馆:
You can use the standard C++ <chrono>
library:
#include <iostream>
#include <chrono>
// long operation to time
int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n-1) + fib(n-2)
}
}
int main() {
auto start_time = std::chrono::high_resolution_clock::now();
fib(12);
auto end_time = std::chrono::high_resolution_clock::now();
auto time = end_time - start_time;
std::cout << "fib(100) took " <<
std::chrono::duration_cast<std::chrono::microseconds>(time).count() << " to run.\n";
}
要记住的一件事是使用 ; chrono>
启用类型安全的通用时序代码,但是为了获得这样的好处,你使用它有点不同于使用哑,类型不安全的时序库,存储持续时间和时间点在类型如 int
。以下是解释某些特定使用场景以及使用非类型库和使用chrono的最佳做法之间的差异的解答: http://stackoverflow.com / a / 15839862/365496
One thing to keep in mind is that using <chrono>
enables type safe, generic timing code but to get that benefit you have use it a bit differently than you would use dumb, type-unsafe timing libraries that store durations and time points in types like int
. Here's an answer that explains some specific usage scenarios and the differences between using untyped libraries and best practices for using chrono: http://stackoverflow.com/a/15839862/365496
Visual Studio标准库实施的维护者已指示在VS2015中已经修复了 high_resolution_clock
的低分辨率使用 QueryPerformanceCounter()
。
The maintainer of Visual Studio's standard library implementation has indicated that the low resolution of high_resolution_clock
has been fixed in VS2015 via the use of QueryPerformanceCounter()
.
这篇关于测量Windows C ++的时间,毫秒或微秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!