xref: /petsc/src/sys/time/cputime.c (revision 2dce792e531186164765a9583d36d03ffc15e9ea)
1 
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 */
6 
7 #include <petscsys.h>  /*I "petscsys.h" I*/
8 #include <petsctime.h> /*I "petsctime.h" I*/
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
20 
21 #if defined(PETSC_HAVE_SYS_TIMES_H)
22 
23   #include <sys/times.h>
24 PetscErrorCode PetscGetCPUTime(PetscLogDouble *t)
25 {
26   struct tms temp;
27 
28   PetscFunctionBegin;
29   times(&temp);
30   *t = ((double)temp.tms_utime) / ((double)CLOCKS_PER_SEC);
31   PetscFunctionReturn(PETSC_SUCCESS);
32 }
33 
34 #elif defined(PETSC_HAVE_CLOCK)
35 
36   #include <time.h>
37 
38 PetscErrorCode PetscGetCPUTime(PetscLogDouble *t)
39 {
40   PetscFunctionBegin;
41   *t = ((double)clock()) / ((double)CLOCKS_PER_SEC);
42   PetscFunctionReturn(PETSC_SUCCESS);
43 }
44 
45 #else
46 
47   #include <sys/time.h>
48   #include <sys/resource.h>
49 
50 /*@
51     PetscGetCPUTime - Returns the CPU time in seconds used by the process.
52 
53     Not Collective
54 
55     Output Parameter:
56 .   t - Time in seconds charged to the process.
57 
58     Example:
59 .vb
60     #include <petscsys.h>
61     ...
62     PetscLogDouble t1, t2;
63 
64     PetscCall(PetscGetCPUTime(&t1));
65     ... code to time ...
66     PetscCall(PetscGetCPUTime(&t2));
67     printf("Code took %f CPU seconds\n", t2-t1);
68 .ve
69 
70     Level: intermediate
71 
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.
77 
78 .seealso: `PetscTime()`, `PetscLogView()`
79 @*/
80 PetscErrorCode PetscGetCPUTime(PetscLogDouble *t)
81 {
82   static struct rusage temp;
83   PetscLogDouble       foo, foo1;
84 
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 }
92 
93 #endif
94