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