Pierre Ossman | 236c03c | 2014-07-04 14:12:49 +0200 | [diff] [blame] | 1 | /* Copyright 2013-2014 Pierre Ossman <ossman@cendio.se> for Cendio AB |
| 2 | * |
| 3 | * This is free software; you can redistribute it and/or modify |
| 4 | * it under the terms of the GNU General Public License as published by |
| 5 | * the Free Software Foundation; either version 2 of the License, or |
| 6 | * (at your option) any later version. |
| 7 | * |
| 8 | * This software is distributed in the hope that it will be useful, |
| 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | * GNU General Public License for more details. |
| 12 | * |
| 13 | * You should have received a copy of the GNU General Public License |
| 14 | * along with this software; if not, write to the Free Software |
| 15 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
| 16 | * USA. |
| 17 | */ |
| 18 | |
| 19 | #include <stdint.h> |
| 20 | |
| 21 | #ifdef WIN32 |
| 22 | #include <windows.h> |
| 23 | #else |
| 24 | #include <sys/resource.h> |
| 25 | #endif |
| 26 | |
| 27 | #ifdef WIN32 |
| 28 | static FILETIME cpuCounters[2]; |
| 29 | #else |
| 30 | struct rusage cpuCounters[2]; |
| 31 | #endif |
| 32 | |
| 33 | static void measureCpu(void *counter) |
| 34 | { |
| 35 | #ifdef WIN32 |
| 36 | FILETIME dummy1, dummy2, dummy3; |
| 37 | |
| 38 | GetProcessTimes(GetCurrentProcess(), &dummy1, &dummy2, |
| 39 | &dummy3, (FILETIME*)counter); |
| 40 | #else |
| 41 | getrusage(RUSAGE_SELF, (struct rusage*)counter); |
| 42 | #endif |
| 43 | } |
| 44 | |
| 45 | void startCpuCounter(void) |
| 46 | { |
| 47 | measureCpu(&cpuCounters[0]); |
| 48 | } |
| 49 | |
| 50 | void endCpuCounter(void) |
| 51 | { |
| 52 | measureCpu(&cpuCounters[1]); |
| 53 | } |
| 54 | |
| 55 | double getCpuCounter(void) |
| 56 | { |
| 57 | double seconds; |
| 58 | |
| 59 | #ifdef WIN32 |
| 60 | uint64_t counters[2]; |
| 61 | |
| 62 | counters[0] = (uint64_t)cpuCounters[0].dwHighDateTime << 32 | |
| 63 | cpuCounters[0].dwLowDateTime; |
| 64 | counters[1] = (uint64_t)cpuCounters[1].dwHighDateTime << 32 | |
| 65 | cpuCounters[1].dwLowDateTime; |
| 66 | |
| 67 | seconds = (double)(counters[1] - counters[2]) / 10000000.0; |
| 68 | #else |
| 69 | seconds = (double)(cpuCounters[1].ru_utime.tv_sec - |
| 70 | cpuCounters[0].ru_utime.tv_sec); |
| 71 | seconds += (double)(cpuCounters[1].ru_utime.tv_usec - |
| 72 | cpuCounters[0].ru_utime.tv_usec) / 1000000.0; |
| 73 | #endif |
| 74 | |
| 75 | return seconds; |
| 76 | } |