xref: /petsc/src/sys/time/cputime.c (revision 2f6eced2a19e978d64f27de66fbc6c26cc5c7934)
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(0);
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(0);
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     ierr = PetscGetCPUTime(&t1);CHKERRQ(ierr);
65     ... code to time ...
66     ierr = PetscGetCPUTime(&t2);CHKERRQ(ierr);
67     printf("Code took %f CPU seconds\n", t2-t1);
68 .ve
69 
70     Level: intermediate
71 
72     Notes:
73     One should use PetscTime() or the -log_summary 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 PetscErrorCode  PetscGetCPUTime(PetscLogDouble *t)
79 {
80   static struct rusage temp;
81   PetscLogDouble       foo,foo1;
82 
83   PetscFunctionBegin;
84   getrusage(RUSAGE_SELF,&temp);
85   foo  = temp.ru_utime.tv_sec;        /* seconds */
86   foo1 = temp.ru_utime.tv_usec;       /* uSecs */
87   *t   = foo + foo1 * 1.0e-6;
88   PetscFunctionReturn(0);
89 }
90 
91 #endif
92