我有一个大问题,我自己创建了链表和数据结构,但数据读取功能运行速度很慢。如果我尝试读取10k结构函数需要大约530毫秒:
List size: 10000
Time: 530
Delete success
Press any key to continue . . .
但是当我尝试读取10倍数据量(它是100k)时,需要大约44500毫秒:
List size: 100000
Time: 44512
Delete success
Press any key to continue . . .
这是我的代码:
IQ_struct.h
#ifndef IQ_sturct_H
#define IQ_struct_H
class IQ_struct {
public:
IQ_struct();
void setIQ(float, float);
float getIQ();
float getIQx();
float getIQy();
~IQ_struct();
private:
float newX;
float newY;
};
#endif
IQ_struct.cpp
#include "IQ_struct.h"
IQ_struct::IQ_struct(){
newX = 0;
newY = 0;
}
IQ_struct::~IQ_struct(){}
void IQ_struct::setIQ(float x, float y){
newX = x;
newY = y;
}
float IQ_struct::getIQx(){
return newX;
}
float IQ_struct::getIQy(){
return newY;
}
IQ_data.h
#include <string>
#include "IQ_struct.h";
#ifndef IQ_data_H
#define IQ_data_H
class IQ_data{
public:
IQ_data();
void AddData(float, float);
void Begin();
void Next();
bool End();
IQ_struct GetData();
void ReadFromFile(std::string,int);
int GetSize();
~IQ_data();
private:
typedef struct TNode{
IQ_struct data;
TNode *next;
}* nodePtr;
nodePtr head;
nodePtr curr;
nodePtr temp;
int size;
};
#endif
IQ_data.cpp
#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include "IQ_data.h"
using namespace std;
IQ_data::IQ_data(){
head = NULL;
curr = NULL;
temp = NULL;
size = 0;
}
void IQ_data::AddData(float x, float y){
nodePtr n = new TNode;
n->next = NULL;
n->data.setIQ(x,y);
if(head != NULL){
curr = head;
while(curr->next != NULL){
curr = curr->next;
}
curr->next = n;
}else{
head = n;
}
}
void IQ_data::Begin(){
curr = head;
}
void IQ_data::Next(){
curr = curr->next;
}
bool IQ_data::End(){
return curr == NULL;
}
IQ_struct IQ_data::GetData(){
return curr->data;
}
void IQ_data::ReadFromFile(string fileName,int a){
float x,y;
fstream myfile(fileName, ios_base::in);
for(int k = 0; k < a; k++){
myfile >> x;
myfile >> y;
AddData(x,y);
size = size + 1;
}
myfile.close();
}
int IQ_data::GetSize(){
return size;
}
IQ_data::~IQ_data(){
while (head != NULL){
curr = head;
head = head->next;
delete curr;
}
delete temp;
delete head;
curr = NULL;
delete curr;
cout << "Delete success \n";
}
Main.cpp的
#include <iostream>
#include <fstream>
#include <omp.h>
#include <time.h>
#include <cstdlib>
#include "IQ_data.h"
using namespace std;
int main(){
IQ_data listas;
clock_t init, fin;
init = clock();
listas.ReadFromFile("0.0013.txt",100000);
fin = clock() - init;
cout <<"List size: "<< listas.GetSize() << endl;
cout <<"Time: "<<fin<<endl;
return 0;
}
我做错了什么?主要问题是我的文件包含超过5000K的结构。 提前感谢您的帮助:)
答案 0 :(得分:3)
您正在添加到列表的末尾,因此您需要每次遍历整个列表,这会随着列表变长而延长。
要么添加到列表的头部,要么保留指向最后一个元素的指针,以便您可以快速插入。