小编use*_*022的帖子

C++向量与数组(时间)

我和我在这里有两个程序,两个程序完成相同的任务.它们只是将布尔数组/向量设置为值true.使用向量的程序需要27秒才能运行,而涉及大小为5倍的数组的程序则需要不到1秒.我想知道为什么会有这么大的差异的确切原因?载体真的效率低吗?

程序使用向量

#include <iostream>
#include <vector>
#include <ctime>

using namespace std;

int main(){
 const int size = 2000;
 time_t start, end;
 time(&start);
 vector<bool> v(size);
 for(int i = 0; i < size; i++){
  for(int j = 0; j < size; j++){
   v[i] = true;
  }
 }
 time(&end);
 cout<<difftime(end, start)<<" seconds."<<endl;
}
Run Code Online (Sandbox Code Playgroud)

运行时 - 27秒

使用Array编程

#include <iostream>
#include <ctime>

using namespace std;

int main(){
 const int size = 10000; // 5 times more size
 time_t start, end;
 time(&start);
 bool v[size];
 for(int …
Run Code Online (Sandbox Code Playgroud)

c++ arrays performance time vector

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

arrays ×1

c++ ×1

performance ×1

time ×1

vector ×1