Advertisement
Guest User

time.c

a guest
May 10th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. #include <unistd.h>
  7.  
  8. #define NS_IN_S 1000000000L
  9.  
  10. void usage();
  11. void display_results(char**, double);
  12.  
  13. int main(int argc, char **argv) {
  14.     pid_t pid;
  15.  
  16.     if (argc < 2)
  17.         usage();
  18.  
  19.     pid = fork();
  20.  
  21.     if (pid == -1) {
  22.         perror("fork()");
  23.         exit(1);
  24.     }
  25.     else if (!pid) {                    /* Child executes program */
  26.         execvp(argv[1], argv + 1);
  27.         perror("exec()");
  28.         exit(1);
  29.     }
  30.     else {                              /* Parent waits and times */
  31.         struct timespec start, end;
  32.         double duration;                /* In seconds */
  33.         int status;
  34.  
  35.         /* Record start time */
  36.         if (clock_gettime(CLOCK_MONOTONIC, &start) == -1) {
  37.             perror("clock_gettime()");
  38.             exit(1);
  39.         }
  40.  
  41.         /* Wait on our child */
  42.         waitpid(pid, &status, 0);  
  43.  
  44.         /* Only display results if program exits normally */
  45.         if (WIFEXITED(status)) {
  46.             if (clock_gettime(CLOCK_MONOTONIC, &end) == -1) {
  47.                 perror("clock_gettime()");
  48.                 exit(1);
  49.             }
  50.             duration = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / NS_IN_S;
  51.             display_results(argv, duration);
  52.         }
  53.         else
  54.             fprintf(stderr, "Child process did not exit normally\n");
  55.     }
  56.  
  57.     return 0;
  58. }
  59.  
  60. void usage() {
  61.     fprintf(stderr, "\n\t ./time <command> [args]\n\n");
  62.     exit(2);
  63. }
  64.  
  65. void display_results(char **argv, double duration) {
  66.     char **ptr = argv + 1;
  67.     while(*ptr){
  68.         printf("%s ", *ptr);
  69.         ptr++;
  70.     }
  71.     printf("took %lf seconds\n", duration);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement