1 /* Copyright (c) 2007-2014 Massachusetts Institute of Technology
3 * Permission is hereby granted, free of charge, to any person obtaining
4 * a copy of this software and associated documentation files (the
5 * "Software"), to deal in the Software without restriction, including
6 * without limitation the rights to use, copy, modify, merge, publish,
7 * distribute, sublicense, and/or sell copies of the Software, and to
8 * permit persons to whom the Software is furnished to do so, subject to
9 * the following conditions:
11 * The above copyright notice and this permission notice shall be
12 * included in all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "nlopt-util.h"
25 #ifdef TIME_WITH_SYS_TIME
26 # include <sys/time.h>
29 # ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
36 #if defined(_WIN32) || defined(__WIN32__)
40 /* return time in seconds since some arbitrary point in the past */
41 double nlopt_seconds(void)
43 static THREADLOCAL int start_inited = 0; /* whether start time has been initialized */
44 #if defined(HAVE_GETTIMEOFDAY)
45 static THREADLOCAL struct timeval start;
49 gettimeofday(&start, NULL);
51 gettimeofday(&tv, NULL);
52 return (tv.tv_sec - start.tv_sec) + 1.e-6 * (tv.tv_usec - start.tv_usec);
53 #elif defined(HAVE_TIME)
55 #elif defined(_WIN32) || defined(__WIN32__)
56 static THREADLOCAL ULONGLONG start;
60 GetSystemTimeAsFileTime(&ft);
61 start = (((ULONGLONG) ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
63 GetSystemTimeAsFileTime(&ft);
64 return 100e-9 * (((((ULONGLONG) ft.dwHighDateTime) << 32) + ft.dwLowDateTime) - start);
66 /* use clock() as a fallback... this is somewhat annoying
67 because clock() may wrap around with a fairly short period */
68 static THREADLOCAL clock_t start;
73 return (clock() - start) * 1.0 / CLOCKS_PER_SEC;
77 /* number based on time for use as random seed */
78 unsigned long nlopt_time_seed(void)
80 #if defined(HAVE_GETTIMEOFDAY)
82 gettimeofday(&tv, NULL);
83 return (tv.tv_sec ^ tv.tv_usec);
84 #elif defined(HAVE_TIME)
86 #elif defined(_WIN32) || defined(__WIN32__)
88 GetSystemTimeAsFileTime(&ft);
89 return ft.dwHighDateTime ^ ft.dwLowDateTime;