I want to do time in C++. Not tell the user what the date is or what the time is now, but instead calculate how much time it takes to do something. I want to know how you do it or if there are any good tutorials on this general topic.
Thanks
I want to do time in C++. Not tell the user what the date is or what the time is now, but instead calculate how much time it takes to do something. I want to know how you do it or if there are any good tutorials on this general topic.
Thanks
Last edited by darknite135; 12-22-2007 at 07:06 PM. Reason: Added more content and elaborated ^^
Well, you need a function to get the current time. You call it before the block you want to time. You call it again afterwards. Then you take the difference.
time() is a possibility, but an inaccurate one, whereas clock() is more accurate, but on some implementations only measures actual CPU time. Other than that, there's only non-portable stuff, like the *nix gettimeofday() or the Win32 GetTickCount() or timeGetTime().
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
This is what I get:
Time is the difference between..say...timestart...and time end.
What I don't get:
How would you i implement this and make a function?
I really need an example.
Thanks! xD
Like CornedBee said, time is inaccurate, but if you need a simple example, here'se one from C++ Reference:
Code:/* difftime example */ #include <stdio.h> #include <time.h> int main () { time_t start,end; char szInput [256]; double dif; time (&start); printf ("Please, enter your name: "); gets (szInput); time (&end); dif = difftime (end,start); printf ("Hi %s.\n", szInput); printf ("It took you %.2lf seconds to type your name.\n", dif ); return 0; }
A bad one insofar as that you should never ever use gets. But it demonstrates the timing.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
Yeah - I just copied that straight from the other website. Here's a C++ version:
Code:/* difftime example */ #include <iostream> #include <string> #include <time.h> int main (void) { time_t start,end; std::string name; double dif; time (&start); std::cout << "Please enter your name:" << std::endl; std::getline(std::cin, name); time (&end); dif = difftime (end,start); std::cout << "Hi "<< name << "." << std::endl; std::cout << "It took you " << dif << " seconds to type your name.\n"; return 0; }
Last edited by mikeman118; 12-23-2007 at 08:52 AM. Reason: Forgot a header
Thanks everyone, I get it now xD. Hmm now to make a simple application that tells you how much time it takes you to type a sentence.