update nearly all FSF copyright year lists to include 2010
[gnulib.git] / lib / times.c
1 /* Get process times
2
3    Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* Written by Simon Josefsson <simon@josefsson.org>, 2008.  */
20
21 #include <config.h>
22
23 /* Get times prototype. */
24 #include <sys/times.h>
25
26 /* Get round. */
27 #include <math.h>
28
29 /* Get GetProcessTimes etc. */
30 #include <windows.h>
31
32 static clock_t
33 filetime2clock (FILETIME time)
34 {
35   float f;
36
37   /* We have a 64-bit value, in the form of two DWORDS aka unsigned
38      int, counting the number of 100-nanosecond intervals.  We need to
39      convert these to clock ticks.  Older POSIX uses CLK_TCK to
40      indicate the number of clock ticks per second while modern POSIX
41      uses sysconf(_SC_CLK_TCK).  Mingw32 does not appear to have
42      sysconf(_SC_CLK_TCK), but appears to have CLK_TCK = 1000 so we
43      use it.  Note that CLOCKS_PER_SEC constant does not apply here,
44      it is for use with the clock function.  */
45
46   f = (unsigned long long) time.dwHighDateTime << 32;
47   f += time.dwLowDateTime;
48   f = f * CLK_TCK / 10000000;
49   return (clock_t) round (f);
50 }
51
52 clock_t
53 times (struct tms * buffer)
54 {
55   FILETIME creation_time, exit_time, kernel_time, user_time;
56
57   if (GetProcessTimes (GetCurrentProcess (), &creation_time, &exit_time,
58                        &kernel_time, &user_time) == 0)
59     return (clock_t) -1;
60
61   buffer->tms_utime = filetime2clock (user_time);
62   buffer->tms_stime = filetime2clock (kernel_time);
63   buffer->tms_cutime = 0;
64   buffer->tms_cstime = 0;
65
66   return filetime2clock (creation_time);
67 }