Code about converting seconds into a stopwatch.

AFAIK this code is finished, but is there anything i can do to make this code run any faster?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main() {
    int totalSec, sec, min, hour;
    cout << "Number of seconds: "; cin >> totalSec;
    hour = totalSec / 3600;
    min = (totalSec % 3600) / 60;
    sec = totalSec - (hour * 3600) - (min * 60);

    cout << "Hours: " << hour << endl;
    cout << "Minutes: " << min << endl;
    cout << "Seconds: " << sec << endl;

    return 0;
}
It runs pretty fast as it stands.

Minor tweaks?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main()
{
   int sec, min, hour;
   cout << "Number of seconds: ";    cin >> sec;
   hour = sec / 3600;   sec -= hour * 3600; 
   min  = sec / 60;     sec -= min * 60;

   cout << "Hours: "   << hour << '\n'
        << "Minutes: " << min  << '\n'
        << "Seconds: " << sec  << '\n';
}
Last edited on
Thank you very much for answering ^^.
Yeah that'll decrease the memory used and even avoiding some minor bugs.

thanks!
cout is relatively slow. if you are using this in some sort of timer / stopwatch capacity, minimize the number of output statements and it will perform a little better.
Thanks for replying!
I know for sure that cout is slower in some cases, but for avoiding typing-error i'll stick to cout/cin for a while. Thanks for pointing that out though!
What exactly do you think is slow about your program?
Here's something that you can do to speed things up (and make speed-testing more accurate), but is only going to work in an actual terminal or console which many novice users are not comfortable using. I say try to cut out the user from the speed equation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <sstream>
// includes and using namespace, etc.

int main(int argc, char ** argv)
{
    if(argc == 2)
    {
        stringstream ss;
        ss << argv[1];
        int seconds;
        ss >> seconds;
    }
    else
    {
        // get seconds via cin and cout, or explain how to use the program from console and exit
        // you can get piped input from a script if you accept cin input at this point.
    }
    // continue with your code from there...
}


The user could then provide the argument from outside the program, instead of holding up its execution time.
Last edited on
Topic archived. No new replies allowed.