C++ char*转vector性能分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010164190/article/details/88419894
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;

int main(){
  char buffer[1000000] = {0};
  clock_t start,end;
  
  cout << "sizeof(buffer) = " << sizeof(buffer) << endl;
  for(int i = 0; i < sizeof(buffer); i++){
    buffer[i] = i;
  }
  
  //第一种方式
  start=clock();
  vector<char> data(buffer, buffer + sizeof(buffer));
  end=clock();
  printf("data: total time = %fms\n",(float)(end - start) / CLOCKS_PER_SEC * 1000);

  //第二种方式:push_back
  vector<char> str;
  start=clock();
  for(int i = 0; i < sizeof(buffer); i++){
    str.push_back(buffer[i]);
  }
  end=clock();
  printf("push_back: total time = %fms\n",(float)(end - start) / CLOCKS_PER_SEC * 1000);
}

总结:第一种方式更快!

猜你喜欢

转载自blog.csdn.net/u010164190/article/details/88419894