xref: /petsc/src/sys/time/cputime.c (revision 2205254efee3a00a594e5e2a3a70f74dcb40bc03)
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 <ctype.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #if defined(PETSC_HAVE_STDLIB_H)
12 #include <stdlib.h>
13 #endif
14 #if defined(PETSC_HAVE_SYS_UTSNAME_H)
15 #include <sys/utsname.h>
16 #endif
17 #if defined(PETSC_HAVE_TIME_H)
18 #include <time.h>
19 #endif
20 #if defined(PETSC_HAVE_SYS_SYSTEMINFO_H)
21 #include <sys/systeminfo.h>
22 #endif
23 
24 #if defined(PETSC_HAVE_SYS_TIMES_H)
25 
26 #include <sys/times.h>
27 #include <limits.h>
28 #undef __FUNCT__
29 #define __FUNCT__ "PetscGetCPUTime"
30 PetscErrorCode  PetscGetCPUTime(PetscLogDouble *t)
31 {
32   struct tms temp;
33 
34   PetscFunctionBegin;
35   times(&temp);
36   *t = ((double)temp.tms_utime)/((double)CLOCKS_PER_SEC);
37   PetscFunctionReturn(0);
38 }
39 
40 #elif defined(PETSC_HAVE_CLOCK)
41 
42 #include <time.h>
43 #include <sys/types.h>
44 
45 #undef __FUNCT__
46 #define __FUNCT__ "PetscGetCPUTime"
47 PetscErrorCode  PetscGetCPUTime(PetscLogDouble *t)
48 {
49   PetscFunctionBegin;
50   *t = ((double)clock()) / ((double)CLOCKS_PER_SEC);
51   PetscFunctionReturn(0);
52 }
53 
54 #else
55 
56 #include <sys/types.h>
57 #include <sys/time.h>
58 #include <sys/resource.h>
59 
60 #undef __FUNCT__
61 #define __FUNCT__ "PetscGetCPUTime"
62 /*@
63     PetscGetCPUTime - Returns the CPU time in seconds used by the process.
64 
65     Not Collective
66 
67     Output Parameter:
68 .   t - Time in seconds charged to the process.
69 
70     Example:
71 .vb
72     #include <petscsys.h>
73     ...
74     PetscLogDouble t1, t2;
75 
76     ierr = PetscGetCPUTime(&t1);CHKERRQ(ierr);
77     ... code to time ...
78     ierr = PetscGetCPUTime(&t2);CHKERRQ(ierr);
79     printf("Code took %f CPU seconds\n", t2-t1);
80 .ve
81 
82     Level: intermediate
83 
84     Notes:
85     One should use PetscGetTime() or the -log_summary option of
86     PETSc for profiling. The CPU time is NOT a realistic number to
87     use since it does not include the time for message passing etc.
88     Also on many systems the accuracy is only on the order of microseconds.
89 @*/
90 PetscErrorCode  PetscGetCPUTime(PetscLogDouble *t)
91 {
92   static struct rusage temp;
93   PetscLogDouble       foo,foo1;
94 
95   PetscFunctionBegin;
96   getrusage(RUSAGE_SELF,&temp);
97   foo  = temp.ru_utime.tv_sec;        /* seconds */
98   foo1 = temp.ru_utime.tv_usec;       /* uSecs */
99   *t   = foo + foo1 * 1.0e-6;
100   PetscFunctionReturn(0);
101 }
102 
103 #endif
104