By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,148 Members | 1,339 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,148 IT Pros & Developers. It's quick & easy.

Need help in timing program

ilikepython
Expert 100+
P: 844
I wrote a program that generates random numbers. I want to make it so that it gives me the time it took to complete the program. Here's my code:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <ctime>
  3. #include <cstdlib>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8.     float timer = time(0);
  9.     srand((unsigned)time(0));
  10.     int numofnums = 100;
  11.     int nums[numofnums];
  12.     for (int x = 0; x < numofnums; x++){
  13.         nums[x] = rand()%10 + 1;
  14.         cout << nums[x] << endl;}
  15.     float timed = (unsigned)time(0) - timer;
  16.     cout << "TIME: "<< (unsigned)timed << endl << timer << endl << time(0) << endl; //print to see what is going on
  17.     system("PAUSE");
  18.     return 0;}
  19.  
The problem is that when I run it the "timed" prints out to a big number usually in between 20-100. The "time(0)" at the end works fine as it is a little higher everytime. I think the problem is that the time doesn't update everytime I run the program. What can I do?

I have the Bloodshed DEV compiler.
Thanks in advance.
Mar 21 '07 #1
Share this Question
Share on Google+
2 Replies


Roonie
P: 99
i think that since time(0) returns an integer number of seconds, storing it in a float is inappropriate.

i tried this:
Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <iostream>
  3. #include <ctime>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     long timer = time(0);
  11.     srand(time(0));
  12.     int numofnums = 100;
  13.     int nums[100];
  14.     for (int x = 0; x < numofnums; x++){
  15.         nums[x] = rand()%10 + 1;
  16.         cout << nums[x] << endl;}
  17.     long timed = time(0) - timer;
  18.     cout << "TIME: "<< (unsigned)timed << endl << timer << endl << time(0) << endl; //print to see what is going on
  19.     system("PAUSE");
  20.     return 0;
  21. }
  22.  
and it seemed to give a more reasonable value for the elapsed time. (zero seconds as opposed to 40-50.)
Mar 21 '07 #2

ilikepython
Expert 100+
P: 844
Thank you, now it works just fine.
Mar 21 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.