Actual source code: cputime.c


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

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

 21: #if defined(PETSC_HAVE_SYS_TIMES_H)

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

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

 34: #elif defined(PETSC_HAVE_CLOCK)

 36:   #include <time.h>

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

 45: #else

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

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

 53:     Not Collective

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

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

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

 70:     Level: intermediate

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

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

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

 93: #endif