0

Is there a way to use the unix 'time' command in C++ and store each of its outputs in a variable?

EDIT: If there isn't a way, then what about calling time in a bash script and storing the returned values some way?

Thank you!

2
  • 1
    Is there a particular reason that you don't want to use the time function, and the various functions that format time_t variables? E.g. stackoverflow.com/questions/2242963/…. Commented Feb 26, 2012 at 4:46
  • Yes, I tried a few such functions - I had a problem to compile clock_gettime, and all the other time functions I tried that did compile had other problems. time() for example gave me diff in integer, others gave me diff in double but it was the CPU time and not clock time (the 'real' in the unix time command). Commented Feb 26, 2012 at 4:49

3 Answers 3

1

Supposing you are on UNIX, then the C++ standard std::system function will behave as defined in POSIX, that is, execute a command as with sh. Before doing this, you can connect your own stdin and stdout to a local pipe by first using dup to create aliases of STDIN_FILENO and STDOUT_FILENO, then close the aforementioned file descriptors, then pipe to open a pipe on the newly freed descriptors.

Then you can interact with std::cin and std::cout. Well, it would be a good idea to flush the C++ interface before beginning.

This isn't all really a good idea, though. It should be simpler to use the POSIX C interface to get the relevant data directly.

Sign up to request clarification or add additional context in comments.

1 Comment

As you mention, I'm looking for a simpler solution. But it's good to know, thanks!
1

If you are ok with using Boost libraries, then this should do it http://www.boost.org/doc/libs/1_49_0/doc/html/date_time/examples.html#date_time.examples.seconds_since_epoch

the good part is it also handles time zones conversions :)

Comments

0

You can use system(3) or popen(3), but there's almost always a better, more portable, and native solution, depending on what exactly you're looking for. In your specific case it seems like what you're really looking for a combination of getrusage(2) and ftime(3).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.