Advertisement
jacknpoe

Tempo de execução de alocações em C/C++

Jan 20th, 2024 (edited)
1,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | Source Code | 0 0
  1. #include <iostream>  // cout
  2. #include <cstdlib>  // allocs
  3. #include <time.h>  // clock
  4. #include <locale>  // setlocale
  5.  
  6. #define ITERACOES 1000000
  7.  
  8. int main() {
  9.     clock_t clock1, clock2;
  10.     char *buffer1, *buffer2;
  11.  
  12.     std::cout.precision(4);
  13.     setlocale( LC_ALL, "");     // caracteres acentuados
  14.  
  15.     std::cout << "Resolução: " << CLOCKS_PER_SEC << " tiques por segundo." << std::endl;
  16.  
  17.     clock1 = clock();
  18.     for( int indice = 1; indice <= ITERACOES; indice++)
  19.     {
  20.         buffer1 = (char *) malloc( indice);
  21.         buffer1[indice-1] = indice;
  22.         buffer2 = (char *) malloc( indice);
  23.         buffer2[indice-1] = indice;
  24.         free( buffer1);
  25.         free( buffer2);
  26.     }
  27.     clock2 = clock();
  28.  
  29.     std::cout << "Malloc: " << double( (clock2 - clock1 )) / CLOCKS_PER_SEC << "s" << std::endl;
  30.  
  31.     clock1 = clock();
  32.     for( int indice = 1; indice <= ITERACOES; indice++)
  33.     {
  34.         buffer1 = (char *) calloc( indice, 1);
  35.         buffer1[indice-1] = indice;
  36.         buffer2 = (char *) calloc( indice, 1);
  37.         buffer2[indice-1] = indice;
  38.         free( buffer1);
  39.         free( buffer2);
  40.     }
  41.     clock2 = clock();
  42.  
  43.     std::cout << "Calloc: " << double( ( clock2 - clock1 )) / CLOCKS_PER_SEC << "s" << std::endl;
  44.  
  45.     buffer1 = (char *) malloc( 1);
  46.     buffer2 = (char *) malloc( 1);
  47.     clock1 = clock();
  48.     for( int indice = 1; indice <= ITERACOES; indice++)
  49.     {
  50.         buffer1 = (char *) realloc( buffer1, indice);
  51.         buffer1[indice-1] = indice;
  52.         buffer2 = (char *) realloc( buffer2, indice);
  53.         buffer2[indice-1] = indice;
  54.     }
  55.     free( buffer1);
  56.     free( buffer2);
  57.     clock2 = clock();
  58.  
  59.     std::cout << "Realloc: " << double( (clock2 - clock1 )) / CLOCKS_PER_SEC << "s" << std::endl;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement