SHARE
TWEET

Array and vector performance

Archon Dec 8th, 2010 95 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <cstdlib>
  5. #include <ctime>
  6.  
  7. #define SIZE 100
  8. #define ACCESSES 1000000
  9.  
  10. void testArray(){
  11.    int t = time(0);
  12.    std::cout << "array: ";
  13.    int a[SIZE];
  14.    for (int i = 0; i != ACCESSES; ++i)
  15.       a[rand() % SIZE] = rand();
  16.    std::cout << time(0) - t << "s" << std::endl;
  17. }
  18.  
  19. void testVector(){
  20.    int t = time(0);
  21.    std::cout << "vector: ";
  22.    std::vector<int> a(SIZE);
  23.    for (int i = 0; i != ACCESSES; ++i)
  24.       a[rand() % SIZE] = rand();
  25.    std::cout << time(0) - t << "s" << std::endl;
  26. }
  27.  
  28. void testList(){
  29.    int t = time(0);
  30.    std::cout << "list: ";
  31.    std::list<int> a(SIZE);
  32.    for (int i = 0; i != ACCESSES; ++i){
  33.       int index = rand() % SIZE;
  34.       std::list<int>::iterator it = a.begin();
  35.       for (int counter = 0; counter != index; ++counter, ++it)
  36.          ;
  37.       *it = rand();
  38.    }
  39.    std::cout << time(0) - t << "s" << std::endl;
  40. }
  41.  
  42. int main(){
  43.    for (int i = 0; i != 4; ++i){
  44.       testArray();
  45.       testVector();
  46.       testList();
  47.    }
  48. }
RAW Paste Data
Want to get better at C++?
Learn to code C++ in 2017
Top