БлогNot. Шаблон класса динамического массива и консольная измерялка свободной памяти

Шаблон класса динамического массива и консольная измерялка свободной памяти

В коде заметки приведён небольшой шаблонный класс динамического массива и функция-измерялка использования памяти memory, показывающая соответствующие данные в консоли во время работы программы.

Создаётся 100000 целочисленных массивов по 10000 случайных элементов, каждую 1000 шагов проверяется использование памяти.

У меня всё время работы программы память "стоит на месте", колеблясь лишь в нормальных для Windows пределах. Разумеется, если в процессе открывать новые вкладки, запускать приложения и т.п., картина изменится. Ну и встроенные средства диагностики в Studio есть.

Консольный листинг на C++ проверялся в актуальной сборке Visual Studio 2019.

Собирать это нужно в стандарте C++14, будет ли работать в более высоких - не факт.

#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include <ctime>

using namespace std;

template <class T> class Array {
private:
 T* list; 
 int size;
public:
 Array(int size = 2);
 Array(const Array<T>& a);
 ~Array();
 Array<T>& operator =(const Array<T>& rhs);
 T& operator [](int i);
 const T& operator [](int i) const;
 operator T* ();
 int getSize() const;
 void reSize(int _size);
};

template<class T> Array<T>::Array(int _size) {
 assert(_size >= 0);
 size = _size;
 list = new T[size];
}

template<class T> Array<T>::~Array() {
 delete[] list;
}

template<class T> Array<T>::Array(const Array<T>& a) {
 size = a.size;
 list = new T[size];
 for (int i = 0; i < size; i++) {
  list[i] = a.list[i];
 }
}

template<class T> Array<T>& Array<T>::operator =(const Array<T>& rhs) {
 if(&rhs != this) { 
  if(size != rhs.size) {
   delete[] list;
   size = rhs.size;
   list = new T[size];
  }
  for(int i = 0; i < size; i++) {
   list[i] = rhs[i];
  }
 }
 return *this;
}

template<class T> T& Array<T>::operator [](int n) {
 assert(n >= 0 && n < size);
 return list[n];
}

template<class T> const T& Array<T>::operator [](int n) const {
 assert(n >= 0 && n < size);
 return list[n];
}

template<class T> Array<T>::operator T* () {
 return list;
}

template<class T> int Array<T>::getSize() const {
 return size;
}

template<class T> void Array<T>::reSize(int _size) {
 assert(_size >= 0);
 if (_size == size) {
  return;
 }
 T* newlist = new T[_size];
 int n = _size < size ? _size : size;
 for (int i = 0; i < n; i++) {
  newlist[i] = list[i];
 }
 delete[] list;
 list = newlist;
 size = _size;
}

#include<windows.h>
#include<tchar.h>

void memory() { //Измерялка использования памяти
 MEMORYSTATUSEX statex;
 const int DIV = 1048576; //Меряем в Мб
 const int WIDTH = 7;
 statex.dwLength = sizeof(statex);
 GlobalMemoryStatusEx(&statex);
 system("cls");
 _tprintf(TEXT("There is  %*ld percent of memory in use.\n"), 
  WIDTH, statex.dwMemoryLoad);
 _tprintf(TEXT("There are %*I64d total Mbytes of physical memory.\n"), 
  WIDTH, statex.ullTotalPhys / DIV);
 _tprintf(TEXT("There are %*I64d free Mbytes of physical memory.\n"), 
  WIDTH, statex.ullAvailPhys / DIV);
 _tprintf(TEXT("There are %*I64d total Mbytes of paging file.\n"), 
  WIDTH, statex.ullTotalPageFile / DIV);
 _tprintf(TEXT("There are %*I64d free Mbytes of paging file.\n"), 
  WIDTH, statex.ullAvailPageFile / DIV);
 _tprintf(TEXT("There are %*I64d total Mbytes of virtual memory.\n"), 
  WIDTH, statex.ullTotalVirtual / DIV);
 _tprintf(TEXT("There are %*I64d free Mbytes of virtual memory.\n"), 
  WIDTH, statex.ullAvailVirtual / DIV);
 _tprintf(TEXT("There are %*I64d free Mbytes of extended memory.\n"), 
  WIDTH, statex.ullAvailExtendedVirtual / DIV);
}

int main() {
 srand(time(NULL));
 for (int k = 0; k < 100000; k++) {
  Array <int> a(10000);
  for (int i = 0; i < a.getSize(); i++) {
   a[i] = rand()%10000;
  }
  a.reSize(20000);
  for (int i = 10000; i < a.getSize(); i++) {
   a[i] = rand() % 20000;
  }
  if (k % 1000 == 0) memory();
 }
 return 0;
}

21.05.2021, 16:15 [967 просмотров]


теги: учебное c++ random studio

К этой статье пока нет комментариев, Ваш будет первым