【发布时间】:2019-08-19 10:32:53
【问题描述】:
作为一个练习,我试图衡量两种算法的效率,它们应该执行相同的任务,排序一个堆栈,只使用一个堆栈作为支持数据结构:
#include <stack>
#include <iostream>
#include <chrono>
std::stack<int> sortStack(std::stack<int>& inS){
std::stack<int> tmpS;
int tmpV=0;
tmpS.push(inS.top());
inS.pop();
while(!inS.empty()){
if(inS.top()>=tmpS.top()){
tmpS.push(inS.top());
inS.pop();
}else{
tmpV = inS.top();
inS.pop();
int count = 0;
//reverse the stack until we find the item that is smaller
while(!tmpS.empty()){
if(tmpS.top()>tmpV){
inS.push(tmpS.top());
tmpS.pop();
count++;
}else{
break;
}
}
//tmpS.top is smaller (or =) than tmpV
tmpS.push(tmpV);
//and revert the other stack
for(int i=0; i< count; i++){
tmpS.push(inS.top());
inS.pop();
}
}
}
return tmpS;
}
std::stack<int> sortStackRevisited(std::stack<int>& inS){
std::stack<int> tmpS;
int tmpV=0;
while(!inS.empty()){
tmpV = inS.top();
inS.pop();
//reverse the stack until we find the item that is smaller
while(!tmpS.empty() && tmpS.top()>tmpV){
inS.push(tmpS.top());
tmpS.pop();
}
tmpS.push(tmpV);
}
return tmpS;
}
int main(){
using namespace std::chrono;
std::stack<int> s1({1,0,123,3,5,89,23,12,1000});
std::stack<int> s({1,0,123,3,5,89,23,12,1000});
auto t1 = high_resolution_clock::now() ;
std::stack<int> ordered = sortStackRevisited(s);
auto t2 = high_resolution_clock::now() ;
std::stack<int> ordered2 = sortStack(s1);
auto t3 = high_resolution_clock::now() ;
std::cout<<"\n";
std::cout<<duration_cast<microseconds>(t2-t1).count()<<" "<<duration_cast<microseconds>(t3-t2).count()<<"\n";
}
运行这个程序,我始终得到 t2 - t1 大于 t3- t2。如果我更改函数调用的顺序,即:
auto t1 = high_resolution_clock::now() ;
std::stack<int> ordered = sortStack(s);
auto t2 = high_resolution_clock::now() ;
std::stack<int> ordered2 = sortStackRevisited(s1);
auto t3 = high_resolution_clock::now() ;
我仍然认为 t2 - t1 大于 t3- t2。怎么了?我错过了什么吗?
编译我使用g++ --std=c++11 sortStack.cpp
【问题讨论】:
-
Why is it faster to process a sorted array than an unsorted array? 的可能重复项。编辑:没关系,我以为你在同一个容器上工作了两次。
-
-O2或-O3会发生什么? -
一般来说,当像这样计时,你想多次运行每个算法,测量,例如,运行算法 1000 次所需的总时间,然后计算一次的平均时间从那跑。尤其是这么小的数据集,每次运行都会很快,以至于只测量一次运行的结果基本上只是噪音......
-
嗯,您必须记住,您(很可能)在现代操作系统上运行,该操作系统具有在现代超标量处理器之上运行的抢占式多任务处理。这里有各种各样的效果。第一次运行将预热缓存。由于您的数据和代码很小,仅此一项就可能导致任何后续运行显着加快(这就是为什么人们通常会丢弃前几次运行的结果以允许老化期)。
-
也可能是程序的启动恰好持续占用足够的时间,以使您的线程在第一个算法被挂起之前到达它的开始。由于单个运行几乎不需要时间,例如,这可能导致第一次运行被分成两个心跳,而第二次运行则在一个心跳中运行。您在这里测量的是执行到达程序中某些点之间的间隔时间(包括从其他应用程序运行线程所花费的潜在时间),而不是 CPU 在您的进程中花费的实际周期数......
标签: c++ algorithm performance performance-testing chrono