ARTICLE AD BOX
I am trying to make a command similar to time in Ubuntu that will give me the time taken by the command which follows it on the command prompt.
My logic here is to use fork to create a duplicate process within my program and run the second command using this process. I get the time value just before the start of, and just after the end of, the forked process and then display the difference between these two time values. I could think of no other method to get control back from the second program back to the first.
Clearly, this is inferior to the built-in time command in Ubuntu, and that could be one reason why my values don't exactly match the values reported by time.
Can you please explain the logic of the built-in time command, and how I could improve my program? Of course, I just want to display the overall time taken by the process. To measure the "user" and "sys" times is well beyond my current ability level.
My code:
include <iostream> #include <cerrno> #include <cstring> #include <unistd.h> #include <sys/wait.h> #include <sys/time.h> int main(int argc, char *argv[]) { long long int min, hr, day, i; double seconds, seconds1; struct timeval tv_start, tv_end; errno = 34; int idp = getpid(), idc; idc = fork(); char **arglist = new char *[argc]; for (int i = 0; i < argc - 1; i++) arglist[i] = argv[i + 1]; arglist[argc - 1] = NULL; gettimeofday(&tv_start, NULL); // start of process if (idc == -1) { std::cerr << "fork() failed" << std::endl; exit(1); } if (idc == 0) { execvp(argv[1], arglist); if (errno != 0) { std::cout << "process failed, error code: " << errno << ": " << std::strerror(errno) << std::endl; exit(2); } } else { waitpid(idc, NULL, 0); gettimeofday(&tv_end, NULL); // end of process seconds = (tv_end.tv_sec - tv_start.tv_sec) + (double)(tv_end.tv_usec - tv_start.tv_usec) / 1000000; min = (long long int)seconds / 60; seconds = seconds - min * 60; hr = min / 60; min = min % 60; day = hr / 24; hr = hr % 24; std::cout << std::endl << "execution time: "; std::cout << day << " days, " << hr << " hrs, " << min << " min, " << seconds << " sec" << std::endl; } delete[] arglist; arglist = nullptr; return 0; }