I have written this code to variably test Prim's algorithm and I am timing it using clock(). For some reason it always returns 0 as its running time. I have other code that I have used this exact implementation in and they are returning the currect running times. The code is very short and if anyone has any idea of why this is happening please let me know. I only have 4 more hours left on this project. Thanks in advance!

#include <iostream>
#include <stdio.h>
#include <ctime>
#include <cstdlib>
using namespace std;

int main(){

    int a,b,u,v,n,i,j,ne;
    ne = 1;

    int visited[1000] = {0},min,mincost=0,cost[1000][1000];

cout << "Enter the number of nodes:" << endl;
cin >> n;
for(int i=1; i<n; i++)
for(int j=1; j<=n; j++)
        {
            cost[i][j] = (rand()%1000)+1;

        }
visited[1]=1;
cout << endl;

clock_t t;
float running_time;

while(ne<n)
 {
  for(i=1,min=1000;i<=n;i++)
   for(j=1;j<=n;j++)
    if(cost[i][j]<min)
     if(visited[i]!=0)
     {
      min=cost[i][j];
      a=u=i;
      b=v=j;
     }
  if(visited[u]==0 || visited[v]==0)
  {
   cout << "Edge: " << ne++ << endl;
   cout << a << " " << b << endl;
   cout << "Cost: " << min << endl;
   mincost+=min;
   visited[b]=1;
  }
  cost[a][b]=cost[b][a]=1000;
 }
 cout << "Min cost: " << mincost << endl;

    t = clock();
    t = clock() - t;
    running_time = ((float)t/CLOCKS_PER_SEC);
    cout << "The running time of this algorithm is: " << running_time << " seconds" << endl;

return 0;
}

Recommended Answers

All 4 Replies

The problem is with lines 51-52:

t = clock();
t = clock() - t;

which is the same as t = clock() - clock();, which is the same as t = 0;. So, that's why you get zero all the time.

You need to use two different clock_t variables, such as t1 and t2. set t1 before doing anything, such as on line 27, then set t2 after finishing, such as on line 50. Then just subtract the two. But, be warned that computers are very very fast so the difference is likely to be at or close to 0.

And i guess he need to initialize the first clock outside the while loop so that there will be a difference in the starting and outside the finished while loop get a new clock to minus the starting time from the ending time and the results is the time taken. Like a lazy benchmark 101.

something like this should do the trick ...

unsigned int start = 0, end =0;
start = time(0);
........your code goes here ...
end = time(0);
cout <<"Total Runtime = " <<end - start <<endl;

        ***** HAVE PHUN C0DiNG*****
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.