Actual source code: cputime.c

  1: /*
  2:   This is to allow one to measure CPU time usage of their job,
  3:   NOT real time usage. Do not use this for reported timings, speedup etc.
  4: */

  6: #include <petscsys.h>
  7: #include <petsctime.h>
  8: #include <ctype.h>
  9: #include <sys/stat.h>
 10: #if defined(PETSC_HAVE_SYS_UTSNAME_H)
 11:   #include <sys/utsname.h>
 12: #endif
 13: #if defined(PETSC_HAVE_TIME_H)
 14:   #include <time.h>
 15: #endif
 16: #if defined(PETSC_HAVE_SYS_SYSTEMINFO_H)
 17:   #include <sys/systeminfo.h>
 18: #endif

 20: #if defined(PETSC_HAVE_SYS_TIMES_H)

 22:   #include <sys/times.h>
 23: PetscErrorCode PetscGetCPUTime(PetscLogDouble *t)
 24: {
 25:   struct tms temp;

 27:   PetscFunctionBegin;
 28:   times(&temp);
 29:   *t = ((double)temp.tms_utime) / ((double)CLOCKS_PER_SEC);
 30:   PetscFunctionReturn(PETSC_SUCCESS);
 31: }

 33: #elif defined(PETSC_HAVE_CLOCK)

 35:   #include <time.h>

 37: PetscErrorCode PetscGetCPUTime(PetscLogDouble *t)
 38: {
 39:   PetscFunctionBegin;
 40:   *t = ((double)clock()) / ((double)CLOCKS_PER_SEC);
 41:   PetscFunctionReturn(PETSC_SUCCESS);
 42: }

 44: #else

 46:   #include <sys/time.h>
 47:   #include <sys/resource.h>

 49: /*@
 50:     PetscGetCPUTime - Returns the CPU time in seconds used by the process.

 52:     Not Collective

 54:     Output Parameter:
 55: .   t - Time in seconds charged to the process.

 57:     Example:
 58: .vb
 59: #include <petscsys.h>
 60:     ...
 61:     PetscLogDouble t1, t2;

 63:     PetscCall(PetscGetCPUTime(&t1));
 64:     ... code to time ...
 65:     PetscCall(PetscGetCPUTime(&t2));
 66:     printf("Code took %f CPU seconds\n", t2-t1);
 67: .ve

 69:     Level: intermediate

 71:     Note:
 72:     One should use the -log_view option of
 73:     PETSc for profiling. The CPU time is NOT a realistic number to
 74:     use since it does not include the time for message passing etc.
 75:     Also on many systems the accuracy is only on the order of microseconds.

 77: .seealso: `PetscTime()`, `PetscLogView()`
 78: @*/
 79: PetscErrorCode PetscGetCPUTime(PetscLogDouble *t)
 80: {
 81:   static struct rusage temp;
 82:   PetscLogDouble       foo, foo1;

 84:   PetscFunctionBegin;
 85:   getrusage(RUSAGE_SELF, &temp);
 86:   foo  = temp.ru_utime.tv_sec;  /* seconds */
 87:   foo1 = temp.ru_utime.tv_usec; /* uSecs */
 88:   *t   = foo + foo1 * 1.0e-6;
 89:   PetscFunctionReturn(PETSC_SUCCESS);
 90: }

 92: #endif