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