(root)/
coreutils-9.4/
gnulib-tests/
bench.h
       1  /* Utilities for benchmarks.
       2     Copyright (C) 2018-2023 Free Software Foundation, Inc.
       3  
       4     This program is free software: you can redistribute it and/or modify
       5     it under the terms of the GNU General Public License as published by
       6     the Free Software Foundation, either version 3 of the License, or
       7     (at your option) any later version.
       8  
       9     This program is distributed in the hope that it will be useful,
      10     but WITHOUT ANY WARRANTY; without even the implied warranty of
      11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12     GNU General Public License for more details.
      13  
      14     You should have received a copy of the GNU General Public License
      15     along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
      16  
      17  #include <stdio.h>
      18  #include <sys/resource.h>
      19  #include <sys/time.h>
      20  
      21  struct timings_state
      22  {
      23    /* Filled when the timings start.  */
      24    struct timeval real_start;
      25    struct timeval user_start;
      26    struct timeval sys_start;
      27    /* Filled when the timings end.  */
      28    long real_usec;
      29    long user_usec;
      30    long sys_usec;
      31  };
      32  
      33  static void
      34  timing_start (struct timings_state *ts)
      35  {
      36    struct rusage usage;
      37  
      38    getrusage (RUSAGE_SELF, &usage);
      39    ts->user_start = usage.ru_utime;
      40    ts->sys_start = usage.ru_stime;
      41  
      42    gettimeofday (&ts->real_start, NULL);
      43  }
      44  
      45  static void
      46  timing_end (struct timings_state *ts)
      47  {
      48    struct timeval real_end;
      49    struct rusage usage;
      50  
      51    gettimeofday (&real_end, NULL);
      52  
      53    getrusage (RUSAGE_SELF, &usage);
      54  
      55    ts->real_usec = (real_end.tv_sec - ts->real_start.tv_sec) * 1000000
      56                    + real_end.tv_usec - ts->real_start.tv_usec;
      57    ts->user_usec = (usage.ru_utime.tv_sec - ts->user_start.tv_sec) * 1000000
      58                    + usage.ru_utime.tv_usec - ts->user_start.tv_usec;
      59    ts->sys_usec = (usage.ru_stime.tv_sec - ts->sys_start.tv_sec) * 1000000
      60                   + usage.ru_stime.tv_usec - ts->sys_start.tv_usec;
      61  }
      62  
      63  static void
      64  timing_output (const struct timings_state *ts)
      65  {
      66    printf ("real %10.6f\n", (double)ts->real_usec / 1000000.0);
      67    printf ("user %7.3f\n", (double)ts->user_usec / 1000000.0);
      68    printf ("sys  %7.3f\n", (double)ts->sys_usec / 1000000.0);
      69  }