你可以使用标准库中的 <chrono>
头文件:
#include <chrono>
#include <iostream>
unsigned long long fib(unsigned long long n) {
return (0==n || 1==n) ? 1 : fib(n-1) + fib(n-2);
}
int main() {
unsigned long long n = 0;
while (true) {
auto start = std::chrono::high_resolution_clock::now();
fib(++n);
auto finish = std::chrono::high_resolution_clock::now();
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);
std::cout << microseconds.count() << "µs\n";
if (microseconds > std::chrono::seconds(1))
break;
}
}
你需要自己测量时间。我通常使用的小秒表类如下:
#include <chrono>
#include <iostream>
template <typename Clock = std::chrono::steady_clock>
class stopwatch
{
typename Clock::time_point last_;
public:
stopwatch()
: last_(Clock::now())
{}
void reset()
{
*this = stopwatch();
}
typename Clock::duration elapsed() const
{
return Clock::now() - last_;
}
typename Clock::duration tick()
{
auto now = Clock::now();
auto elapsed = now - last_;
last_ = now;
return elapsed;
}
};
template <typename T, typename Rep, typename Period>
T duration_cast(const std::chrono::duration<Rep, Period>& duration)
{
return duration.count() * static_cast<T>(Period::num) / static_cast<T>(Period::den);
}
int main()
{
stopwatch<> sw;
// ...
std::cout << "Elapsed: " << duration_cast<double>(sw.elapsed()) << '\n';
}
duration_cast可能不是一个最佳的函数名称,因为标准库中已经存在具有此名称的函数。随意想出更好的名称。;)
编辑:请注意chrono来自C++11。
对于这个问题,可以使用std::chrono
或者boost::chrono
(如果你的编译器不支持C++11)。
std::chrono::high_resolution_clock::time_point start(
std::chrono::high_resolution_clock::now() );
....
std::cout << (std::chrono::high_resolution_clock::now() - start);
high_resolution_clock
,而不是 high_resolution_timer
。 - Benoit Blanchon您需要编写一个简单的计时系统。C++中没有内置的方法。
#include <sys/time.h>
class Timer
{
private:
struct timeval start_t;
public:
double start() { gettimeofday(&start_t, NULL); }
double get_ms() {
struct timeval now;
gettimeofday(&now, NULL);
return (now.tv_usec-start_t.tv_usec)/(double)1000.0 +
(now.tv_sec-start_t.tv_sec)*(double)1000.0;
}
double get_ms_reset() {
double res = get_ms();
reset();
return res;
}
Timer() { start(); }
};
int main()
{
Timer t();
double used_ms;
// run slow code..
used_ms = t.get_ms_reset();
// run slow code..
used_ms += t.get_ms_reset();
return 0;
}
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
clock_t t1,t2;
t1=clock();
//code goes here
t2=clock();
float diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC;
cout << "Running time: " << diff << endl;
return 0;
}
你也可以这样做:
int start_s=clock();
// the code you wish to time goes here
int stop_s=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;
-pg
的经验是它会破坏许多带有 errno
设置为 EINTR
的调用。是的,修复一个或两个这样的调用很容易。但如果你有 100,000 行代码,那就祝你好运了... - Alexis Wilke#include <ctime>
头文件。它的函数及其用途在这里。假设你想要观察代码花费了多少时间。你必须在该部分开始之前取得当前时间,然后在该部分结束之后再取得另一个当前时间。然后取这两个时间的差值。预先定义好的函数在ctime
中声明,可以完成所有这些工作。只需查看上面的链接即可。