GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 31-Jan-2006, 03:48
cpit cpit is offline
Junior Member
 
Join Date: Jan 2006
Posts: 73
cpit is on a distinguished road

paging file control


Hi friends,

I have a program (c++) that make a .txt file on time of run, but in win XP, when the file arrive to 1003KB the program abort because do not have memory enough.

My computer is a pentium 4, 1GB RAM and 2GB of Virtual Memory.

Does anybody have some explanation?

regards,

CPP / C++ / C Code:
int main() {

  time_t inicio, fim;

  cout.precision(3);
  char buffervert[33];
  char bufferlink[33];
  itoa (vertices,buffervert,10);
  itoa (links,bufferlink,10);

  do{
  cout<<"Enter number of nodes (n): ";
  cin >> vertices;
  }while(vertices<2);

  int matrizO[(vertices*(vertices-1))][3];

  do{
     cout<<"Enter number of links (l) (Between "<<(vertices-1)<<" and "<<((vertices*(vertices-1))/2)<<"): ";
     cin >> links;
  }while((links < (vertices -1)) || (links >((vertices*(vertices-1))/2)));


  char arq[100];
  sprintf(arq, "cb%d_%d.txt", vertices, links);

[b]  arquivo.open (arq);[/b]
   arquivo << "COMBINACOES: "<<endl<<endl;
   arquivo <<"Lista de <h>"<<endl<<endl;

   inicio=time(NULL);
   geracombinacao(links,matrizO);
   fim=time(NULL);

  arquivo<<"\nNumero de Nodos (n)  : "<<vertices<<endl;
  arquivo<<"\nNumero de Links (L)  : "<<links<<endl;
  arquivo<<"\nGrau Medio      ( )  : "<<graumedio<<endl;
  arquivo<<"\nTempo Processo  (t)  : "<<(fim-inicio)<<" Segundos"<<endl;

  delete(matrizO);

  [b]arquivo.close();[/b]  

  system("PAUSE");

  return 0;
}
Last edited by LuciWiz : 31-Jan-2006 at 12:42. Reason: Please insert your C++ code between [c++] & [/c++] tags
  #2  
Old 31-Jan-2006, 09:36
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: paging file control


Quote:
Originally Posted by cpit
Hi friends,

I have a program (c++) that make a .txt file on time of run, but in win XP, when the file arrive to 1003KB the program abort because do not have memory enough.

My computer is a pentium 4, 1GB RAM and 2GB of Virtual Memory.

Does anybody have some explanation?

A couple of things come to mind. The program behavior that you describe could be caused by:

1. The program, with whatever input you gave it, takes a lot of memory.

2. The program has a bug that causes some runaway memory allocation or recursive functionality and runs out of memory with whatever input you gave it.

3. Something else.

I certainly can't help beyond this point since

a. I can't compile your program since it is missing some key features (there are a number of variables and functions that are undefined in the code that you posted).

b. I have no idea what input you gave it.

c. You didn't tell us some very important information: What input did you give it? What is the program supposed to do with whatever input you gave it? What did you expect the output to be? How big did you expect the output file to be? etc.

One debugging technique is to put cout<< (or other output statements) throughout your code at points where functions are called, at points where memory is allocated, at points where the program writes to the file, etc.

This is something you can do, since you have the entire source code.



Regards,

Dave
  #3  
Old 31-Jan-2006, 12:24
cpit cpit is offline
Junior Member
 
Join Date: Jan 2006
Posts: 73
cpit is on a distinguished road

Re: paging file control


Sorry, now i post entire code.

for example, if we give an input of 5 nodes and 6 links, the program do the 210 possible combinations (combinatory), for each combination, the program send it to function Dijsktra that calculate the small patch between the nodes and do a mean of hops for each combination.

The program write each mean of hops in a file.

I got success with 10 nodes and 43 links, but if i try with 10 nodes and 39 links, the program abort when the file has 1.006kb

Its happens about after 1:30 hour of proccess in my P4 3.2, 1GB Ram - win XP with 1056MB of virtual memory (I already did changes here)

Below is the code, and the combination.h file are attached.

regards,


CPP / C++ / C Code:
#include <iostream.h>
#include <fstream.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define INFINITY ((int) pow(2, sizeof(int)*8-2)-1)
#include<vector>
#include<string>
#include "combination.h"
#include <time.h>

int destino, origem, links, vertices=0;
long int cinvalidas=0;
int custo, *custos = NULL;
float graumedio=0;


ofstream arquivo;


void dijkstra(int *mediah, int vertices,int origem,int destino,int *custos, int *flagp)
{
   int i=0,v=0, cont = 0;
   int *ant, *tmp;  
   int *z;     /* vertices para os quais se conhece o caminho minimo */
   double min=0;
   double dist[vertices]; /* vetor com os custos dos caminhos, inicializa com o valor de vertices*/


   /* aloca as linhas da matriz */
   ant = new int[vertices];  //antecessor!.
   tmp = new int[vertices];
   if (ant == NULL) {
      cout<<"** Erro: Memoria Insuficiente **"<<endl;;
      system("PAUSE");
      //exit(-1);
   }

   z = new int[vertices];
   if (z == NULL) {
      cout<<"** Erro: Memoria Insuficiente **"<<endl;
      system("PAUSE");
      //exit(-1);
   }

   for (i = 0; i < vertices; i++) {
      if (custos[(origem - 1) * vertices + i] !=- 1) {
          ant[i] = origem - 1;
          dist[i] = custos[(origem-1)*vertices+i];
      } else {
         ant[i]= -1;
         dist[i] = INFINITY;
      }
      z[i]=0;
   }
   z[origem-1] = 1; // se conhece o caminho, fecha o vertice.
   dist[origem-1] = 0;


   /* Laco principal */
   do {

      /* Encontrando o vertice que deve entrar em z */
      min = INFINITY;
      for (i=0;i<vertices;i++)
         if (!z[i])
            if (dist[i]>=0 && dist[i]<min) {
               min=dist[i];v=i;
            }

      /* Calculando as distancias dos novos vizinhos de z */
      if (min != INFINITY && v != destino - 1) {
         z[v] = 1;
         for (i = 0; i < vertices; i++)
            if (!z[i]) {
               if (custos[v*vertices+i] != -1 && dist[v] + custos[v*vertices+i] < dist[i]) {
                     dist[i] = dist[v] + custos[v*vertices+i];
                  ant[i] =v;
                  }
              }
      }
   } while (v != destino - 1 && min != INFINITY);

   /* Mostra o Resultado da busca */
   if((min == INFINITY) && (origem!=destino)){
      cout<<"\tPROBLEMA"<<"\t";
      //arquivo<<"\tPROBLEMA"<<"\t";
   }else{
      cout<<"\tDe "<<origem<<" para "<<destino<<"\t";
      //arquivo <<"\tDe "<<origem<<" para "<<destino<<"\t";
   }



   if (min == INFINITY) {
         if((min == INFINITY) && (origem!=destino)){
         cout<<"GRAFO DESCONEXO";
         cout<<"\n\tSaltos: \t-"<<endl;
         *flagp=1; //indica que nao será exibido o <h>.
      }else{
         cout<<"Inexistente";
         //arquivo <<"Inexistente";
         cout<<"\n\tSaltos: \t-"<<endl;
         //arquivo<<"\n\tSaltos: \t-"<<endl;
      }

   }
   else {
      i = destino;
      i = ant[i-1];
      while (i != -1) {
           tmp[cont] = i+1;
         cont++;
         i = ant[i];
      }
      
      for (i = cont; i > 0 ; i--) {
           cout<<tmp[i-1]<<" -> ";
           //arquivo <<tmp[i-1]<<" -> ";
      }
      cout<< destino;
      //arquivo<<destino;
      
      cout <<"\n\tSaltos: "<<(int) dist[destino-1]<<endl;
      //arquivo<<"\n\tSaltos: "<<(int) dist[destino-1]<<endl;

      /* Calcula o total de hops na matriz h. Somente se existir caminho*/

         *mediah+=(int)dist[destino-1]; //guarda o num de hops

   }
}

/*----------------------------------------------------------------------------*/
/* Gera as combinacoes pedidas por geracombinacoes() e imprime na tela */
template<class BidIt>

void display(BidIt begin,BidIt end, string *comb1)
{
//ponteiro para uma matriz.

int i=0;
  for (BidIt it=begin;it!=end;++it){
    comb1[i]=*it;   /* Grava uma combinacao na matriz combinacoes - geracombinacoes()*/
    i++;
  }
}
/*----------------------------------------------------------------------------*/


void add(float *ptrgrau, int links,int (*matadd)[3])
{
   if (!custos)
      delete(custos);

   custos = new int[vertices*vertices*vertices];

   for (int i = 0; i <= vertices * vertices; i++){
      custos[i] = -1;
   }

    float grau;

    for(int i=0;i<(links*2);i++){ //preenche a matriz de custos.
          custos[(matadd[i][0]-1) * vertices + matadd[i][1] - 1] = matadd[i][2];

          custos[(matadd[i][1]-1) * vertices + matadd[i][0] - 1] = matadd[i][2];  // para calcular um grafo nao dirigido.

           grau=(float)(i+1)/(vertices);
          *((float*)ptrgrau)=grau;
    }
}
/*----------------------------------------------------------------------------*/

void procurar()
{
   int i, j, hops=0,flag=0;
   float media=0.0;

   cout<<"Lista dos Menores Caminhos no Grafo: "<<endl<<endl;
      for (i = 1; i <= vertices; i++) {
        for (j = 1; j <= vertices; j++){
           dijkstra(&hops,vertices, i,j, custos, &flag);
        }
       cout<<endl;
      }
      if(flag==0){ //flag !=0 == grafo desconexo.
         media=(float)hops/(vertices*(vertices-1));
         cout<<"\nMedia Hops         <h> : "<<media<<endl;
         arquivo<<media<<endl;
      }else{
        cinvalidas++;
      }
}
/*----------------------------------------------------------------------------*/

/* Verifica se a matriz possui todos os nós interligados - retorna 1 se ok*/
int validaMatriz(int (*ptrmat)[3]){

int k=1;
string vet;
char bufferv[33];
   for(int i=0;i<vertices;i++){
      for(int j=0;j<2;j++){
         while(k <= vertices){
            if(ptrmat[i][j]==k){
             //cout<<"procurou "<<k<<" em "<<i<<"-"<<j<<" achou"<<endl;
                   /* entao k vai para o vetor se ainda nao estiver.*/
                if((vet.find((itoa (k,bufferv,10)),0)) == string::npos){
                   vet+=(itoa (k,bufferv,10));
                }
            }else{
               //cout<<"procurou "<<k<<" em "<<i<<"-"<<j<<" NAO achou"<<endl;
            }
            k++;
          }
          k=1;
         //cout<<"vetor : "<<vet<<endl;
      }
   }
   if(vet.size()==vertices){
      //cout<<"Rede valida : "<<vet<<endl;
      return 1;
   }else{
      //cout<<"Rede INvalida : "<<vet<<endl;
      return 0;
      }
}
/*----------------------------------------------------------------------------*/

void geracombinacao(int l, int (*mat)[3]){

cout.precision(3);

vector<string> str;  /* vetor das combinacoes, todas as possibilidades, L1*/
vector<string> str1; /* vetor com numero de links que se quer*/


/* ---> prenche o vetor str. com os links possiveis, na diagonal superior
        para o numero de nós passado. (D1) ex. n=5, gera 20 linhas ---*/

cout<<"Para o numero de vertices informado: "<<vertices<<endl;
for(int i=1;i<=vertices;i++){
   for(int j=1;j<=vertices;j++){
     if(j>i){
      /* transforma o i e j em string para concatenar.*/
      char bufferi[33];
      char bufferj[33];
      itoa (i,bufferi,10);
      itoa (j,bufferj,10);

      std::string ori=bufferi; /* ori = origem */
      std::string dst=bufferj; /* dst = destino */
      std::string conc;
      std::string concinv; /* conc = concatenado inverso*/
      conc = ori + ':' + dst;  /* preenche conc com 1:2, 1:3...*/
         str.push_back (conc); /* Adiciona a string concatenada no final do vetor str */
      cout<<conc<<endl;
     }
   }
}
cout<<"Estas sao as arestas DUPLEX possiveis "<<endl;
system("PAUSE");
/*----------------------------------------------------------------------------*/

/* ---> Preenche o vetor str1 com o numero de linhas a combinar*/

cout<<"De acordo com o pedido por links: "<<l<<endl;
/* preenche o vetor str1*/
   for(int i=0;i<(l);i++){
      str1.push_back (str[i]);
      cout<<str[i]<<endl;
   }
/*----------------------------------------------------------------------------*/


/* Reserva memória para a matriz das combinacoes (uma combinacao)*/

string combinacoes[(l*2)]; /* guarda as combinacoes geradas */

/* gera todas as combinações com  l */

long int count=0;
float *ptrptrgrau; /* ponteiro que aponta para grau de add*/

  do
  {
    display(str1.begin(),str1.end(),combinacoes);
    //somador de combinacoes.
    count++;

    /* Mostra uma combinacao*/
    string source, destination;
    int sourceint, destint, position;
    for(int i=0;i<(l*2);i++){

       if(combinacoes[i]!=""){
          cout<<"Link :  "<<combinacoes[i]<<endl;;
          //arquivo << "Link: " <<combinacoes[i]<<endl;
       }

       /* separa o string e converte em inteiros.*/
       position=combinacoes[i].find(":",0);
       source=combinacoes[i].substr(0,position);
       destination=combinacoes[i].substr(position+1);
       sscanf(source.c_str(), "%d", &sourceint);
       sscanf(destination.c_str(), "%d", &destint);

       /* grava os dados na matrizO*/
       mat[i][0]=sourceint; /* origem */
       mat[i][1]=destint; /* destino */
       mat[i][2]=1; /* valor default para o peso*/
    }
    cout<<endl;


        if(validaMatriz(mat)!=0){
              //cout<<"ESTA MATRIZ EH VALIDA"<<endl;
              add(&graumedio,l,mat);
              procurar(); //funcao dijskstra procura caminhos e <h>
        }else{
          cinvalidas++;
        }


  }
  while(next_combination(str.begin (),str.end (),str1.begin (),str1.end()));


  cout<<"Combinacoes validas: "<<count-cinvalidas<<endl;
  cout<<"Invalidas: "<<cinvalidas<<endl;
  cout<<"Total: " <<count<<endl;

  arquivo<<"\nCombinacoes     ( )  : "<<count-cinvalidas<<endl; /* Grava no arquivo*/

}
/*----------------------------------------------------------------------------*/


int main() {

  time_t inicio, fim;

  cout.precision(3);
  char buffervert[33];
  char bufferlink[33];
  itoa (vertices,buffervert,10);
  itoa (links,bufferlink,10);

  do{
  cout<<"Informe o numero de nos (n) (minimo 2): ";
  cin >> vertices;
  }while(vertices<2);

  int matrizO[(vertices*(vertices-1))][3];  /* matriz com as combinacoes geradas*/

  do{
     cout<<"Informe o numero de links (l) (entre "<<(vertices-1)<<" e "<<((vertices*(vertices-1))/2)<<"): ";
     cin >> links;
  }while((links < (vertices -1)) || (links >((vertices*(vertices-1))/2)));


  char arq[100];
  sprintf(arq, "cb%d_%d.txt", vertices, links);
  arquivo.open (arq);


   arquivo << "COMBINACOES: "<<endl<<endl;
   arquivo <<"Lista de <h>"<<endl<<endl;

   inicio=time(NULL); /* guarda o tempo inicial */
    /* gera as combinacoes e imprime na tela.*/
  geracombinacao(links,matrizO); /* numero de links que se quer aplicar.*/
   fim=time(NULL); /* guarda o tempo final */

  cout<<"\nNumero de Nodos (n)  : "<<vertices<<endl;
  cout<<"\nNumero de Links (L)  : "<<((vertices*graumedio)/2)<<endl;
  cout<<"\nGrau Medio      ( )  : "<<graumedio<<endl;
  cout<<"\nTempo Processo  (t)  : "<<(fim-inicio)<<" Segundos"<<endl;

  arquivo<<"\nNumero de Nodos (n)  : "<<vertices<<endl;
  arquivo<<"\nNumero de Links (L)  : "<<links<<endl;
  arquivo<<"\nGrau Medio      ( )  : "<<graumedio<<endl;
  arquivo<<"\nTempo Processo  (t)  : "<<(fim-inicio)<<" Segundos"<<endl;


  delete(matrizO); //liberar da memória o cont de matrizO.

  arquivo.close();
  system("PAUSE");

  return 0;
}
Last edited by LuciWiz : 31-Jan-2006 at 12:44. Reason: Please insert your C++ code between [c++] & [/c++] tags
  #4  
Old 31-Jan-2006, 12:52
Guidelines Plz Guidelines Plz is offline
Junior Member
 
Join Date: Sep 2005
Posts: 87
Guidelines Plz is on a distinguished road

Re: paging file control


cpit you have been asked many times to place the proper code tags around your code. See LuciWiz's comments on many of your posts (including the above posts).

And you've been asked to read the Guidelines a couple time, too, which also describes the proper use of code tags (guideline #1) and asking questions (guideline #2) so Dave doesn't have to paraphrase the guideline for you as he did above.
__________________

Please read http://www.gidforums.com/t-5566.html. They were written to help you create a request that is readable and has enough information we can actually tell what you need help with.
  #5  
Old 31-Jan-2006, 23:50
kobi_hikri's Avatar
kobi_hikri kobi_hikri is offline
Regular Member
 
Join Date: Apr 2005
Location: Israel
Posts: 431
kobi_hikri has a spectacular aura aboutkobi_hikri has a spectacular aura about

Re: paging file control


Quote:
Its happens about after 1:30 hour of proccess in my P4 3.2, 1GB Ram

Please read this: Dijkstra´s algorithm
The algorithm you are supposed to use is actually used on routers with 12Mhz processor and 2Kb of memory (even on some routers without any processor at all).
Your program takes 1:30 hour ??? think what will happen if I post a message to GID and the local ISP needs 1:30 hour only to determine the shortest path to send the packets through (assuming the network layer uses Dijkstra) ... It's unreasonable.

Reimplement your algorithm, to start with.
Kobi.
__________________
It's actually a one time thing (it just happens alot).
  #6  
Old 01-Feb-2006, 11:49
cpit cpit is offline
Junior Member
 
Join Date: Jan 2006
Posts: 73
cpit is on a distinguished road
Thumbs up

Re: paging file control


OK young,

My worry is not with the time of process, but that the program abort by fault of memory. And I need to test with dijkstra, it´s a work of university.

now, if my code it is correct, then i need to talk to my professor that i need other computer!!

Regards,
  #7  
Old 01-Feb-2006, 13:45
kobi_hikri's Avatar
kobi_hikri kobi_hikri is offline
Regular Member
 
Join Date: Apr 2005
Location: Israel
Posts: 431
kobi_hikri has a spectacular aura aboutkobi_hikri has a spectacular aura about

Re: paging file control


Quote:
Originally Posted by cpit
My worry is not with the time of process, but that the program abort by fault of memory. And I need to test with dijkstra, it´s a work of university.

I understood your problem. I also understand (and did before) that you need to work with dijkstra algorithm for shortest path in a graph.
Check this text:Lecture Outline regarding Dijkstras algorithm

Oh, and don't expect your professor to give you a new computer (it simply won't help). Do you suppose Dijkstra had a Pentium 4 3.2 Ghz ? No, but he did use his brain, which is much stronger and imaginative than your Pentium 4 3.2 Ghz (and so is your brain).

Best regards,
Kobi.
__________________
It's actually a one time thing (it just happens alot).
  #8  
Old 01-Feb-2006, 14:48
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: paging file control


Quote:
Originally Posted by cpit
My worry is not with the time of process, but that the program abort by fault of memory. And I need to test with dijkstra, it´s a work of university.

now, if my code it is correct, then i need to talk to my professor that i need other computer!!

Before you embarrass yourself with your professor, consider that it is just possible that your code is not correct.

Your program may have bugs. There is no way that anyone else should (maybe no way that they can) debug your program. It is up to you.

Here is a very general approach to try to know where to concentrate your debugging efforts. Maybe you can find out where the problem really is. Whether your program has bugs or not, you should at least be able to find out which part of the program is taking so long.

1. In the function procurar(), comment out the call to dijkstra().

CPP / C++ / C Code:
        for (j = 1; j <= vertices; j++){
           //dijkstra(&hops,vertices, i,j, custos, &flag);
        }
Run the program. If it runs to completion, then you begin debugging by looking at what is being fed to dijkstra(), and see if dijkstra() is doing the right thing. If it runs a long time for your particular data input and still doesn't run to completion, then we don't have to look at anything in dijkstra (not now, anyhow). So, go to the next step

2. In the function geracombinacao(), comment out the call to procurar():

CPP / C++ / C Code:
        if(validaMatriz(mat)!=0){
              //cout<<"ESTA MATRIZ EH VALIDA"<<endl;
              add(&graumedio,l,mat);
              //procurar(); //funcao dijskstra procura caminhos e <h>
        }else{
          cinvalidas++;
        }

Run the program. If it runs a long time for your particular data input and still doesn't run to completion, then:

3. In the function geracombinacao(), comment out the call to add().

Run the program. If it runs a long time for your particular data input and still doesn't run to completion, then:

4. In the main() function, comment out the call to geracombinacao().

Run the program. If it runs a long time for your particular data input and still doesn't run to completion, then I'm stuck. But I'm guessing that you may have found something before now.

You should be able to determine where that problem is. That doesn't necessarily tell you (yet) what the problem is, but at least you can forget (for the time being, at least) about bugs in some of the other routines.

If you find that the program runs to completion when you comment out some particular function, then put cout<< statements that show the values that the function is seeing as its arguments. Look at the statements in the loop (or whatever function) where the promlematic function is being called. You will see how many times it is being called, etc.

Let's say the program runs to completion when you comment out the call to add().

Now, to back and uncomment it, but this time, run the program with a few "good" inputs and look carefully at the program output. Since there may be lots and lots of lines scrolling off of the screen from the thousands of cout<< calls, redirect the output to a file so that you can look at the output in a text editor.

Now run the program with the "bad" input data with the output redirected to another file. Hit Control-C after a second or two. Look at this output and compare with previous "good" outputs.

1. Do you understand everything that is in the output file(s)?

2. Is there anything unexpected in the "bad" output file? Does it look like you think it should? Is there anything remarkable in any way? (This is not an invitation for you to show us what is in the file and ask us what is wrong. It is a suggestion that you should know what to expect, and you should spot anything that is wrong. It is your program, not ours.)

3. How many lines of output would you expect for the data that gives the "bad" output? Look carefully at the output. Is it reasonable? What is the difference (from a network point of view, not a program point of view) between "10 nodes, 43 links" and "10 nodes 39 links"? Is there any reason that one would lead in a solution in a second of machine time but the other would take so long and so much memory that it crashes the program?

You have a couple of places where you use new for some variables, and that memory is never deleted in your program. If the program is in some kind of infinite loop somewhere that includes any of these, then that could explain why you run out of memory eventually. A bigger more powerful computer may go longer before it runs out of memory, but it still won't fix a buggy program. (And, by the way, deleting matrizO is a very Bad Thing, you should never delete something that you didn't get from new. I doubt that it causes any bug(s) inside the program, but it definitely can cause a stackdump upon exit. Anyhow, Don't Do That.)

Now, I'm not saying that following any of my hints above is guaranteed to point you directly to a solution, but the idea is: Make the program tell you what it is working on. As a program implementer it is absolutely necessary that you know what to expect at each step.

Now, if it turns out that your output is exactly what you expect, and your algorithm leads to an impossibly large number of steps for the "bad" input data that you observe, then you may want to rethink your approach to whatever function is giving you the problem.


Regards,

Dave
Last edited by davekw7x : 01-Feb-2006 at 15:35.
  #9  
Old 02-Feb-2006, 13:01
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: paging file control


Quote:
Originally Posted by kobi_hikri
The algorithm you are supposed to use is actually used on routers with 12Mhz processor and 2Kb of memory (even on some routers without any processor at all).
Your program takes 1:30 hour ???


An excellent point: the dijkstra() function itself shouldn't take very much time. However...

I'm not sure what the actual assignment was, but the way it is written, this program doesn't just find the shortest path for a given set of nodes and links.

It actually creates all possible paths for the given number of nodes and links, and then checks each possible path for validity (can you get from every node to every other node with the links?), and then it uses dijkstra() to calculate the lengths, etc.

Let's look at some numbers:

For 10 nodes there are a total of 45 possible links.

For 10 nodes and 45 links, there is a only one combination to be considered (all nodes connected to all other nodes by a link).

For 10 nodes and 44 links, there are a total of 45 combinations to be considered. (Take away one of the 45 links in each case.) This is the combinations function "45 things taken one at a time". Of these, five will lead to disconnected graphs (try it), so dijkstra() will be run on the 40 valid combinations of nodes/links.


For 10 nodes and 43 links, there are a total of 990 combinations (45 things taken 2 at a time), and, it turns out, a total of 196 valid combinations.

For 10 nodes and 42 links, there are a total of 14190 combinations (45 things taken 3 at a time), and, it turns out, a total of 3576 valid combinations.

.
.
.

For 10 nodes and 39 links, there are a total of 8145060 combinations (45 things taken 6 at a time), and, it turns out, a total of 3068100 valid combinations.


It may very well take an hour or more just to generate the combinations, let alone test for validity and call dijkstra(). (3500+ seconds would be my estimate on my system, based on some lower level analysis, and ignoring I/O time to write all of this stuff to a file). It very well may be that the program could be written more efficiently, but it turns out that dijkstra() is not the bottleneck (As might have been guessed from my suggested experiment of commenting out the calls to dijkstra().)


To the Original Poster:


OK, so much for explaining how the program might run for a long, long time. How about running out of memory? Well, the "out of memory" messages come from statements close to places where the new operator was used. If the new operator is used for every combination, or even only for valid combinations, it is called millions of times. When I suggested that the Original Poster put cout<< statements to see where and how many times new was called, I had pretty much expected that interested people would actually look at the issue of memory allocation (and in, particular, look for memory leaks). Let's face it: if new is called millions of times with no corresponding delete, systems very well might run out of memory. (Note that my previous comment about an infinite loop is irrelevant here; a loop of a few million iterations will screw the pooch.) More memory is not the answer. A more powerful processor is not the answer (although it might run out of memory faster than the old, slow one, and save you some time waiting for the crash).

I see four places where new is used to get memory, and there is not a single case where that memory is returned to the system.

If anyone wants to know how to check for a memory leak in a long-running program on a Windows machine:

Open the Windows Task Manager (ctrl-alt-delete). Click on the "Performance" tab and keep an eye on the "Commit Charge (K)" part where it shows "Total". This is the total amount of memory (real and swap) used at any given time. This number may fluctuate a few K bytes (or more) depending on what other processes are running. If it creeps inexorably upward, you have a memory leak. When the "Total" approaches the "Limit", then Bad Things happen.

(Linux users may have a GUI application called "System Monitor" or some such thing, or they can simply enter "top" in a terminal window to see a running report of memory used--- and lots of other stuff.)

---End of Text---
---Over and Out---


Regards,

Dave
Last edited by davekw7x : 02-Feb-2006 at 13:57.
  #10  
Old 03-Feb-2006, 08:47
cpit cpit is offline
Junior Member
 
Join Date: Jan 2006
Posts: 73
cpit is on a distinguished road

Re: paging file control


Dave

How do you calculate the value of valid combinations?

because I did not get a value for 10 nodes and 39 links through the program, but I see you calculated. Please, send me your thought.

regards,
 
 

Recent GIDBlogToyota - 2009 May Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 08:44
Help! Some basal questions about MFC xutingnjupt MS Visual C++ / MFC Forum 1 05-Dec-2004 04:38
CD burner wont burn!! robertli55 Computer Hardware Forum 1 18-Jun-2004 11:53
Yet another CD burner problem: Lite-On LSC-24082K Erwin Computer Hardware Forum 1 22-May-2004 12:28

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 06:20.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.