只需使用std::chrono。下面的一般示例将任务“打印 1000 颗星”乘以:
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
int main ()
{
using namespace std::chrono;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
std::cout << "printing out 1000 stars...\n";
for (int i=0; i<1000; ++i) std::cout << "*";
std::cout << std::endl;
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double, std::milli> time_span = t2 - t1;
std::cout << "It took me " << time_span.count() << " milliseconds.";
std::cout << std::endl;
return 0;
}
您无需打印星星,而是将排序算法放在那里并进行时间测量。
如果您打算进行一些基准测试,例如,请不要忘记为您的编译器启用优化标志。对于g++,您需要-O3。这很严重,请检查我没有这样做时发生了什么:Why emplace_back is faster than push_back?
Ps:如果您的编译器不支持c++11,那么您可以在我的Time Measurements (C++) 中查看其他方法。
使用我的Quicksort (C++) 的特定(玩具)示例是:
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
void quickSort(int a[], int first, int last);
int pivot(int a[], int first, int last);
void swap(int& a, int& b);
void swapNoTemp(int& a, int& b);
using namespace std;
using namespace std::chrono;
int main()
{
int test[] = { 7, -13, 1, 3, 10, 5, 2, 4 };
int N = sizeof(test)/sizeof(int);
cout << "Size of test array :" << N << endl;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
// I want to measure quicksort
quickSort(test, 0, N-1);
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double> time_span = t2 - t1;
std::cout << "It took me " << time_span.count() << " seconds.";
std::cout << std::endl;
return 0;
}
现在的输出是:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++11 -O3 main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
Size of test array :8
It took me 3.58e-07 seconds.
就这么简单。基准测试快乐! =)
编辑:
high_resolution_clock::now()函数返回相对于哪个时间的时间?
来自std::chrono:
时间点
对特定时间点的引用,例如一个
生日,今天的黎明,或者下一班火车经过的时候。在这个
库,time_point 类模板的对象通过
使用相对于 epoch 的持续时间(这是一个固定的时间点
对所有使用相同时钟的 time_point 对象通用)。
哪里可以检查这个epoch and time_point example,它会输出:
time_point tp is: Thu Jan 01 01:00:01 1970