我想确定哪个是用于某些操作的更好的容器,因此我必须检查向量与列表的运行时间。
在线参考对于此实现而言非常模糊或过于复杂。
任何帮助将不胜感激
答案 0 :(得分:0)
如果您有权访问C++11
编译器,
#include <chrono>
#include <iostream>
int main()
{
std::chrono::steady_clock::time_point _start(std::chrono::steady_clock::now());
// code you want to time here
std::chrono::steady_clock::time_point _end(std::chrono::steady_clock::now());
std::cout << std::chrono::duration_cast<std::chrono::duration<double>>(
_end - _start).count(); // in seconds, read more about std::chrono
}
答案 1 :(得分:0)
这就是我使用它的方式:
#include <iostream>
#include <chrono>
auto start = std::chrono::high_resolution_clock::now();
... code to measure here ...
auto diff = std::chrono::high_resolution_clock::now() - start;
auto t1 = std::chrono::duration_cast<std::chrono::nanoseconds>(diff);
std::cout << "Loop1: " << t1.count() << std::endl;
您需要使用g++ -std=c++11
编译它,并且只要您有一个可用的C ++ 11编译器和库,它就应该可以工作。
答案 2 :(得分:0)
这是我目前的代码:
#include <iostream>
#include <list>
#include <vector>
#include <chrono>
#include <stdlib.h>
#include <ctime>
using namespace std;
template <typename Container>
void fill_container(Container& c, int n)
{
int v;
for(int i =0; i<n; i++)
{
v= rand() %12;
c.push_back(v);
}
}
template<typename Container>
void print(Container& c, ostream& out =cout)
{
typename Container::iterator itr = c.begin();
cout << "now" ;
while(itr!=c.end())
{
out << *itr << endl;
itr++;
}
}
template <typename Container>
void removeOdd(Container& c)
{
typename Container::iterator itr2 = c.begin();
while(itr2!= c.end())
{
cout << *itr2 << endl;
if(*itr2 %2 != 0 )
{
itr2 = c.erase(itr2);
}
itr2++;
}
}
int main()
{
//Timer ends
std::chrono::steady_clock::time_point _start(std::chrono::steady_clock::now());
// code you want to time here
vector<int> damn;
fill_container(damn, 20);
removeOdd(damn);
print(damn);
std::chrono::steady_clock::time_point _end(std::chrono::steady_clock::now());
std:: cout << std::chrono::duration_cast<std::chrono::duration<double>>( _end - _start).count();
return 0;
}