Оптимизация кода базы данных

Возможный дубликат:
Оптимизация моего кода, моделирующего базу данных< /а>

Привет, друзья!

Я работал над программой, моделирующей небольшую базу данных, к которой я мог бы делать запросы, и после написания кода я выполнил ее, но производительность не очень хорошая. Работает медленнее, чем я ожидал. Я пытался улучшить его, даже используя профилировщики, но я не вижу, как его улучшить. Другая проблема заключается в том, что я начал работать с C++ самостоятельно несколько месяцев назад, так что мои знания все еще очень низки. Поэтому я хотел бы найти решение для повышения производительности.

Меня попросили сделать таким образом. Так что нет SQLite или подобного, поэтому я думаю, что это хороший способ улучшить этот код только с помощью C++.

Позвольте мне объяснить, как работает мой код. Здесь я прикрепил краткий пример того, как работает мой код.

Прежде всего, у меня есть файл .txt, имитирующий таблицу базы данных со случайными строками, разделенными знаком «|». Здесь у вас есть пример таблицы (с 5 строками и 5 столбцами).

Table.txt

0|42sKuG^uM|24465\lHXP|2996fQo\kN|293cvByiV
1|14772cjZ`SN|28704HxDYjzC|6869xXj\nIe|27530EymcTU
2|9041ByZM]I|24371fZKbNk|24085cLKeIW|16945TuuU\Nc
3|16542M[Uz\|13978qMdbyF|6271ait^h|13291_rBZS
4|4032aFqa|13967r^\\`T|27754k]dOTdh|24947]v_uzg

Эта информация в файле .txt считывается моей программой и сохраняется в памяти компьютера. Затем при выполнении запросов я буду обращаться к этой информации, хранящейся в памяти компьютера. Загрузка данных в память компьютера может быть медленным процессом, но доступ к данным позже будет быстрее, что действительно важно для меня.

Здесь у вас есть часть кода, которая считывает эту информацию из файла и сохраняет в компьютере.

Код, считывающий данные из файла Table.txt и сохраняющий их в памяти компьютера

string ruta_base("C:\\a\\Table.txt"); // Folder where my "Table.txt" is found

string temp; // Variable where every row from the Table.txt file will be firstly stored
vector<string> buffer; // Variable where every different row will be stored after separating the different elements by tokens.
vector<ElementSet> RowsCols; // Variable with a class that I have created, that simulated a vector and every vector element is a row of my table

ifstream ifs(ruta_base.c_str());

while(getline( ifs, temp )) // We will read and store line per line until the end of the ".txt" file. 
{
    size_t tokenPosition = temp.find("|"); // When we find the simbol "|" we will identify different element. So we separate the string temp into tokens that will be stored in vector<string> buffer

    while (tokenPosition != string::npos)
    {    
        string element;
        tokenPosition = temp.find("|");      

        element = temp.substr(0, tokenPosition);
        buffer.push_back(element);
        temp.erase(0, tokenPosition+1);
    }

    ElementSet ss(0,buffer); 
    buffer.clear();
    RowsCols.push_back(ss); // We store all the elements of every row (stores as vector<string> buffer) in a different position in "RowsCols" 
}

vector<Table> TablesDescriptor;

Table TablesStorage(RowsCols);
TablesDescriptor.push_back(TablesStorage);

DataBase database(1, TablesDescriptor);

После этого следует ВАЖНАЯ ЧАСТЬ. Предположим, что я хочу сделать запрос и прошу ввести данные. Допустим, мой запрос — это строка «n», а также последовательные кортежи «numTuples» и столбцы «y». (Надо сказать, что количество столбцов определяется десятичным числом «y», которое будет преобразовано в двоичное и покажет нам запрашиваемые столбцы, например, если я запрошу столбцы 54 (00110110 в двоичном формате) I запросит столбцы 2, 3, 5 и 6). Затем я обращаюсь к памяти компьютера с необходимой информацией и сохраняю ее в векторе, показанном вектором. Здесь я показываю вам часть этого кода.

Код для доступа к необходимой информации после моего ввода

int n, numTuples; 
unsigned long long int y;
clock_t t1, t2;

cout<< "Write the ID of the row you want to get more information: " ;
cin>>n; // We get the row to be represented -> "n"

cout<< "Write the number of followed tuples to be queried: " ;
cin>>numTuples; // We get the number of followed tuples to be queried-> "numTuples"

cout<<"Write the ID of the 'columns' you want to get more information: ";
cin>>y; // We get the "columns" to be represented ' "y"

unsigned int r; // Auxiliar variable for the columns path
int t=0; // Auxiliar variable for the tuples path
int idTable;

vector<int> columnsToBeQueried; // Here we will store the columns to be queried get from the bitset<500> binarynumber, after comparing with a mask
vector<string> shownVector; // Vector to store the final information from the query
bitset<500> mask;
mask=0x1;

t1=clock(); // Start of the query time

bitset<500> binaryNumber = Utilities().getDecToBin(y); // We get the columns -> change number from decimal to binary. Max number of columns: 5000

// We see which columns will be queried
for(r=0;r<binaryNumber.size();r++) //
{               
    if(binaryNumber.test(r) & mask.test(r))  // if both of them are bit "1"
    {
        columnsToBeQueried.push_back(r);
    }
    mask=mask<<1;   
}

do
{
    for(int z=0;z<columnsToBeQueried.size();z++)
    {
        int i;
        i=columnsToBeQueried.at(z);

        vector<int> colTab;
        colTab.push_back(1); // Don't really worry about this

        //idTable = colTab.at(i);   // We identify in which table (with the id) is column_i
        // In this simple example we only have one table, so don't worry about this

        const Table& selectedTable = database.getPointer().at(0); // It simmulates a vector with pointers to different tables that compose the database, but our example database only have one table, so don't worry            ElementSet selectedElementSet;

        ElementSet selectedElementSet;

        selectedElementSet=selectedTable.getRowsCols().at(n);
        shownVector.push_back(selectedElementSet.getElements().at(i)); // We save in the vector shownVector the element "i" of the row "n"

    }   
    n=n+1;
    t++;            

}while(t<numTuples);

t2=clock(); // End of the query time

float diff ((float)t2-(float)t1);
float microseconds = diff / CLOCKS_PER_SEC*1000000;

cout<<"The query time is: "<<microseconds<<" microseconds."<<endl;

Определения классов

Здесь я прикрепил некоторые определения классов, чтобы вы могли скомпилировать код и лучше понять, как он работает:

class ElementSet
{
private:
    int id;
    vector<string> elements; 

public:
    ElementSet(); 
    ElementSet(int, vector<string>); 

    const int& getId();
    void setId(int);

    const vector<string>& getElements();
    void setElements(vector<string>);

};

class Table
{
private:
    vector<ElementSet> RowsCols; 

public:
    Table(); 
    Table(vector<ElementSet>); 

    const vector<ElementSet>& getRowsCols();
    void setRowsCols(vector<ElementSet>);
};


class DataBase
{
     private:
        int id;
        vector<Table> pointer; 

     public:
        DataBase(); 
        DataBase(int, vector<Table>); 

    const int& getId();
    void setId(int);

    const vector<Table>& getPointer();
    void setPointer(vector<Table>);

    };

class Utilities
{
        public:
        Utilities();
        static bitset<500> getDecToBin(unsigned long long int);
};

Итак, проблема, которую я получаю, заключается в том, что время моего запроса сильно различается в зависимости от размера таблицы (ему нечего делать с таблицей из 100 строк и 100 столбцов и таблицей с 10000 строк и 1000 столбцов). Это приводит к тому, что производительность моего кода очень низкая для больших таблиц, что действительно важно для меня... У вас есть идеи, как я могу оптимизировать свой код????

Большое спасибо за всю вашу помощь!!! :)


person thomas    schedule 28.03.2011    source источник
comment
Этот вопрос почти идентичен последнему заданному вами по теме. Это очень расплывчато. Попробуйте определить конкретные узкие места (например, с помощью профилировщика), а затем задайте вопросы о них.   -  person Björn Pollex    schedule 28.03.2011
comment
Возможно, будет хорошей идеей свести ваш вопрос к сути. Не могли бы вы просто описать нам, как работает ваша процедура поиска? В этом суть дела; нам действительно не нужно знать, чтобы знать формат файла и т. д.   -  person Extrakun    schedule 28.03.2011