Previous 199869 Revisions Next

r44565 Friday 29th January, 2016 at 10:47:40 UTC by Miodrag Milanović
Added Google Benchmark library (nw)
Included sample benchmark for eminline for native and noasm
Made GoogleTest compile only if tests are compiled
[/trunk].gitignore makefile
[3rdparty/benchmark].gitignore* .travis-setup.sh* .travis.yml* .ycm_extra_conf.py* AUTHORS* CMakeLists.txt* CONTRIBUTING.md* CONTRIBUTORS* LICENSE* README.md* appveyor.yml* mingw.py*
[3rdparty/benchmark/cmake]AddCXXCompilerFlag.cmake* CXXFeatureCheck.cmake* GetGitVersion.cmake* gnu_posix_regex.cpp* posix_regex.cpp* std_regex.cpp* steady_clock.cpp* thread_safety_attributes.cpp*
[3rdparty/benchmark/include/benchmark]benchmark.h* benchmark_api.h* macros.h* reporter.h*
[3rdparty/benchmark/src]CMakeLists.txt* arraysize.h* benchmark.cc* check.h* colorprint.cc* colorprint.h* commandlineflags.cc* commandlineflags.h* console_reporter.cc* csv_reporter.cc* cycleclock.h* internal_macros.h* json_reporter.cc* log.cc* log.h* mutex.h* re.h* re_posix.cc* re_std.cc* reporter.cc* sleep.cc* sleep.h* stat.h* string_util.cc* string_util.h* sysinfo.cc* sysinfo.h* walltime.cc* walltime.h*
[3rdparty/benchmark/test]CMakeLists.txt* basic_test.cc* benchmark_test.cc* cxx03_test.cc* filter_test.cc* fixture_test.cc* options_test.cc*
[benchmarks]eminline_native.cpp* eminline_noasm.cpp* main.cpp*
[scripts]genie.lua
[scripts/src]3rdparty.lua benchmarks.lua* tests.lua
[src/devices/cpu/i86]i86.txt
[src/emu]diimage.cpp luaengine.cpp render.cpp video.cpp video.h
[src/emu/debug]debugcmd.cpp textbuf.cpp
[src/emu/sound]wavwrite.cpp
[src/emu/ui]miscmenu.cpp selgame.h ui.cpp
[src/lib/util]corealloc.h
[src/mame]mess.lst
[src/mame/drivers]fidel6502.cpp fidelz80.cpp hh_cop400.cpp hh_tms1k.cpp iteagle.cpp mmodular.cpp overdriv.cpp pulsar.cpp tispeak.cpp
[src/mame/includes]fidelz80.h overdriv.h
[src/mame/machine]iteagle_fpga.cpp iteagle_fpga.h
[src/osd/sdl]sdlfile.cpp

trunk/.gitignore
r253076r253077
22/*
33/*/
44!/3rdparty/
5!/benchmarks/
56!/artwork/
67!/docs/
78!/hash/
trunk/3rdparty/benchmark/.gitignore
r0r253077
1*.a
2*.so
3*.so.?*
4*.dll
5*.exe
6*.dylib
7*.cmake
8!/cmake/*.cmake
9*~
10*.pyc
11__pycache__
12
13# lcov
14*.lcov
15/lcov
16
17# cmake files.
18/Testing
19CMakeCache.txt
20CMakeFiles/
21cmake_install.cmake
22
23# makefiles.
24Makefile
25
26# in-source build.
27bin/
28lib/
29/test/*_test
30
31# exuberant ctags.
32tags
33
34# YouCompleteMe configuration.
35.ycm_extra_conf.pyc
36
37# ninja generated files.
38.ninja_deps
39.ninja_log
40build.ninja
41install_manifest.txt
42rules.ninja
43
44# out-of-source build top-level folders.
45build/
46_build/
trunk/3rdparty/benchmark/.travis-setup.sh
r0r253077
1#!/usr/bin/env bash
2
3# Before install
4
5sudo add-apt-repository -y ppa:kalakris/cmake
6if [ "$STD" = "c++11" ]; then
7    sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
8    if [ "$CXX" = "clang++" ]; then
9        wget -O - http://llvm.org/apt/llvm-snapshot.gpg.key | sudo apt-key add -
10        sudo add-apt-repository -y "deb http://llvm.org/apt/precise/ llvm-toolchain-precise-3.6 main"
11    fi
12fi
13sudo apt-get update -qq
14
15# Install
16sudo apt-get install -qq cmake
17if [ "$STD" = "c++11" ] && [ "$CXX" = "g++" ]; then
18    sudo apt-get install -qq gcc-4.8 g++-4.8
19    sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 90
20    sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 90
21elif [ "$CXX" = "clang++" ]; then
22    sudo apt-get install -qq clang-3.6
23    sudo update-alternatives --install /usr/local/bin/clang   clang   /usr/bin/clang-3.6 90
24    sudo update-alternatives --install /usr/local/bin/clang++ clang++ /usr/bin/clang++-3.6 90
25    export PATH=/usr/local/bin:$PATH
26fi
trunk/3rdparty/benchmark/.travis.yml
r0r253077
1language: cpp
2
3# NOTE: The COMPILER variable is unused. It simply makes the display on
4# travis-ci.org more readable.
5matrix:
6    include:
7        - compiler: gcc
8          env: COMPILER=g++-4.6     STD=c++0x BUILD_TYPE=Coverage
9        - compiler: gcc
10          env: COMPILER=g++-4.6     STD=c++0x BUILD_TYPE=Debug
11        - compiler: gcc
12          env: COMPILER=g++-4.6     STD=c++0x BUILD_TYPE=Release
13        - compiler: gcc
14          env: COMPILER=g++-4.8     STD=c++11 BUILD_TYPE=Debug
15        - compiler: gcc
16          env: COMPILER=g++-4.8     STD=c++11 BUILD_TYPE=Release
17        - compiler: clang
18          env: COMPILER=clang++-3.6 STD=c++11 BUILD_TYPE=Debug
19        - compiler: clang
20          env: COMPILER=clang++-3.6 STD=c++11 BUILD_TYPE=Release
21
22before_script:
23    - source .travis-setup.sh
24    - mkdir build && cd build
25
26install:
27  - if [ "${BUILD_TYPE}" == "Coverage" -a "${TRAVIS_OS_NAME}" == "linux" ]; then
28      PATH=~/.local/bin:${PATH};
29      pip install --user --upgrade pip;
30      pip install --user cpp-coveralls;
31    fi
32
33script:
34    - cmake .. -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DCMAKE_CXX_FLAGS="-std=${STD}"
35    - make
36    - make CTEST_OUTPUT_ON_FAILURE=1 test
37
38after_success:
39  - if [ "${BUILD_TYPE}" == "Coverage" -a "${TRAVIS_OS_NAME}" == "linux" ]; then
40      coveralls --include src --include include --gcov-options '\-lp' --root .. --build-root .;
41    fi
trunk/3rdparty/benchmark/.ycm_extra_conf.py
r0r253077
1import os
2import ycm_core
3
4# These are the compilation flags that will be used in case there's no
5# compilation database set (by default, one is not set).
6# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
7flags = [
8'-Wall',
9'-Werror',
10'-pendantic-errors',
11'-std=c++0x',
12'-fno-strict-aliasing',
13'-O3',
14'-DNDEBUG',
15# ...and the same thing goes for the magic -x option which specifies the
16# language that the files to be compiled are written in. This is mostly
17# relevant for c++ headers.
18# For a C project, you would set this to 'c' instead of 'c++'.
19'-x', 'c++',
20'-I', 'include',
21'-isystem', '/usr/include',
22'-isystem', '/usr/local/include',
23]
24
25
26# Set this to the absolute path to the folder (NOT the file!) containing the
27# compile_commands.json file to use that instead of 'flags'. See here for
28# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
29#
30# Most projects will NOT need to set this to anything; you can just change the
31# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
32compilation_database_folder = ''
33
34if os.path.exists( compilation_database_folder ):
35  database = ycm_core.CompilationDatabase( compilation_database_folder )
36else:
37  database = None
38
39SOURCE_EXTENSIONS = [ '.cc' ]
40
41def DirectoryOfThisScript():
42  return os.path.dirname( os.path.abspath( __file__ ) )
43
44
45def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
46  if not working_directory:
47    return list( flags )
48  new_flags = []
49  make_next_absolute = False
50  path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
51  for flag in flags:
52    new_flag = flag
53
54    if make_next_absolute:
55      make_next_absolute = False
56      if not flag.startswith( '/' ):
57        new_flag = os.path.join( working_directory, flag )
58
59    for path_flag in path_flags:
60      if flag == path_flag:
61        make_next_absolute = True
62        break
63
64      if flag.startswith( path_flag ):
65        path = flag[ len( path_flag ): ]
66        new_flag = path_flag + os.path.join( working_directory, path )
67        break
68
69    if new_flag:
70      new_flags.append( new_flag )
71  return new_flags
72
73
74def IsHeaderFile( filename ):
75  extension = os.path.splitext( filename )[ 1 ]
76  return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
77
78
79def GetCompilationInfoForFile( filename ):
80  # The compilation_commands.json file generated by CMake does not have entries
81  # for header files. So we do our best by asking the db for flags for a
82  # corresponding source file, if any. If one exists, the flags for that file
83  # should be good enough.
84  if IsHeaderFile( filename ):
85    basename = os.path.splitext( filename )[ 0 ]
86    for extension in SOURCE_EXTENSIONS:
87      replacement_file = basename + extension
88      if os.path.exists( replacement_file ):
89        compilation_info = database.GetCompilationInfoForFile(
90          replacement_file )
91        if compilation_info.compiler_flags_:
92          return compilation_info
93    return None
94  return database.GetCompilationInfoForFile( filename )
95
96
97def FlagsForFile( filename, **kwargs ):
98  if database:
99    # Bear in mind that compilation_info.compiler_flags_ does NOT return a
100    # python list, but a "list-like" StringVec object
101    compilation_info = GetCompilationInfoForFile( filename )
102    if not compilation_info:
103      return None
104
105    final_flags = MakeRelativePathsInFlagsAbsolute(
106      compilation_info.compiler_flags_,
107      compilation_info.compiler_working_dir_ )
108  else:
109    relative_to = DirectoryOfThisScript()
110    final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )
111
112  return {
113    'flags': final_flags,
114    'do_cache': True
115  }
trunk/3rdparty/benchmark/AUTHORS
r0r253077
1# This is the official list of benchmark authors for copyright purposes.
2# This file is distinct from the CONTRIBUTORS files.
3# See the latter for an explanation.
4#
5# Names should be added to this file as:
6#   Name or Organization <email address>
7# The email address is not required for organizations.
8#
9# Please keep the list sorted.
10
11Arne Beer <arne@twobeer.de>
12Christopher Seymour <chris.j.seymour@hotmail.com>
13David Coeurjolly <david.coeurjolly@liris.cnrs.fr>
14Dominic Hamon <dma@stripysock.com>
15Eugene Zhuk <eugene.zhuk@gmail.com>
16Evgeny Safronov <division494@gmail.com>
17Felix Homann <linuxaudio@showlabor.de>
18Google Inc.
19JianXiong Zhou <zhoujianxiong2@gmail.com>
20Kaito Udagawa <umireon@gmail.com>
21Lei Xu <eddyxu@gmail.com>
22Matt Clarkson <mattyclarkson@gmail.com>
23Oleksandr Sochka <sasha.sochka@gmail.com>
24Paul Redmond <paul.redmond@gmail.com>
25Radoslav Yovchev <radoslav.tm@gmail.com>
26Shuo Chen <chenshuo@chenshuo.com>
27Yusuke Suzuki <utatane.tea@gmail.com>
28Dirac Research
29Zbigniew Skowron <zbychs@gmail.com>
30Dominik Czarnota <dominik.b.czarnota@gmail.com>
trunk/3rdparty/benchmark/CMakeLists.txt
r0r253077
1cmake_minimum_required (VERSION 2.8.11)
2project (benchmark)
3
4option(BENCHMARK_ENABLE_TESTING "Enable testing of the benchmark library." ON)
5option(BENCHMARK_ENABLE_LTO "Enable link time optimisation of the benchmark library." OFF)
6# Make sure we can import out CMake functions
7list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
8
9# Read the git tags to determine the project version
10include(GetGitVersion)
11get_git_version(GIT_VERSION)
12
13# Tell the user what versions we are using
14string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" VERSION ${GIT_VERSION})
15message("-- Version: ${VERSION}")
16
17# The version of the libraries
18set(GENERIC_LIB_VERSION ${VERSION})
19string(SUBSTRING ${VERSION} 0 1 GENERIC_LIB_SOVERSION)
20
21# Import our CMake modules
22include(CheckCXXCompilerFlag)
23include(AddCXXCompilerFlag)
24include(CXXFeatureCheck)
25
26# Try and enable C++11. Don't use C++14 because it doesn't work in some
27# configurations.
28add_cxx_compiler_flag(-std=c++11)
29if (NOT HAVE_CXX_FLAG_STD_CXX11)
30  add_cxx_compiler_flag(-std=c++0x)
31endif()
32
33# Turn compiler warnings up to 11
34if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
35  add_cxx_compiler_flag(-W4)
36  add_definitions(-D_CRT_SECURE_NO_WARNINGS)
37else()
38  add_cxx_compiler_flag(-Wall)
39endif()
40add_cxx_compiler_flag(-Wextra)
41add_cxx_compiler_flag(-Wshadow)
42add_cxx_compiler_flag(-Werror RELEASE)
43add_cxx_compiler_flag(-pedantic)
44add_cxx_compiler_flag(-pedantic-errors)
45add_cxx_compiler_flag(-Wshorten-64-to-32)
46add_cxx_compiler_flag(-Wfloat-equal)
47add_cxx_compiler_flag(-Wzero-as-null-pointer-constant)
48add_cxx_compiler_flag(-fstrict-aliasing)
49if (HAVE_CXX_FLAG_FSTRICT_ALIASING)
50  add_cxx_compiler_flag(-Wstrict-aliasing)
51endif()
52add_cxx_compiler_flag(-Wthread-safety)
53if (HAVE_WTHREAD_SAFETY)
54  add_definitions(-DHAVE_WTHREAD_SAFETY)
55  cxx_feature_check(THREAD_SAFETY_ATTRIBUTES)
56endif()
57
58# Link time optimisation
59if (BENCHMARK_ENABLE_LTO)
60  add_cxx_compiler_flag(-flto)
61  if ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU")
62    find_program(GCC_AR gcc-ar)
63    if (GCC_AR)
64      set(CMAKE_AR ${GCC_AR})
65    endif()
66    find_program(GCC_RANLIB gcc-ranlib)
67    if (GCC_RANLIB)
68      set(CMAKE_RANLIB ${GCC_RANLIB})
69    endif()
70  endif()
71endif()
72
73# Coverage build type
74set(CMAKE_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_DEBUG}" CACHE STRING
75  "Flags used by the C++ compiler during coverage builds."
76  FORCE)
77set(CMAKE_EXE_LINKER_FLAGS_COVERAGE
78  "${CMAKE_EXE_LINKER_FLAGS_DEBUG}" CACHE STRING
79  "Flags used for linking binaries during coverage builds."
80  FORCE)
81set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE
82  "${CMAKE_SHARED_LINKER_FLAGS_DEBUG}" CACHE STRING
83  "Flags used by the shared libraries linker during coverage builds."
84  FORCE)
85mark_as_advanced(
86  CMAKE_CXX_FLAGS_COVERAGE
87  CMAKE_EXE_LINKER_FLAGS_COVERAGE
88  CMAKE_SHARED_LINKER_FLAGS_COVERAGE)
89set(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING
90  "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Coverage."
91  FORCE)
92add_cxx_compiler_flag(--coverage COVERAGE)
93
94# C++ feature checks
95cxx_feature_check(STD_REGEX)
96cxx_feature_check(GNU_POSIX_REGEX)
97cxx_feature_check(POSIX_REGEX)
98cxx_feature_check(STEADY_CLOCK)
99
100# Ensure we have pthreads
101find_package(Threads REQUIRED)
102
103# Set up directories
104include_directories(${PROJECT_SOURCE_DIR}/include)
105
106# Build the targets
107add_subdirectory(src)
108
109if (BENCHMARK_ENABLE_TESTING)
110  enable_testing()
111  add_subdirectory(test)
112endif()
trunk/3rdparty/benchmark/CONTRIBUTING.md
r0r253077
1# How to contribute #
2
3We'd love to accept your patches and contributions to this project.  There are
4a just a few small guidelines you need to follow.
5
6
7## Contributor License Agreement ##
8
9Contributions to any Google project must be accompanied by a Contributor
10License Agreement.  This is not a copyright **assignment**, it simply gives
11Google permission to use and redistribute your contributions as part of the
12project.
13
14  * If you are an individual writing original source code and you're sure you
15    own the intellectual property, then you'll need to sign an [individual
16    CLA][].
17
18  * If you work for a company that wants to allow you to contribute your work,
19    then you'll need to sign a [corporate CLA][].
20
21You generally only need to submit a CLA once, so if you've already submitted
22one (even if it was for a different project), you probably don't need to do it
23again.
24
25[individual CLA]: https://developers.google.com/open-source/cla/individual
26[corporate CLA]: https://developers.google.com/open-source/cla/corporate
27
28Once your CLA is submitted (or if you already submitted one for
29another Google project), make a commit adding yourself to the
30[AUTHORS][] and [CONTRIBUTORS][] files. This commit can be part
31of your first [pull request][].
32
33[AUTHORS]: AUTHORS
34[CONTRIBUTORS]: CONTRIBUTORS
35
36
37## Submitting a patch ##
38
39  1. It's generally best to start by opening a new issue describing the bug or
40     feature you're intending to fix.  Even if you think it's relatively minor,
41     it's helpful to know what people are working on.  Mention in the initial
42     issue that you are planning to work on that bug or feature so that it can
43     be assigned to you.
44
45  1. Follow the normal process of [forking][] the project, and setup a new
46     branch to work in.  It's important that each group of changes be done in
47     separate branches in order to ensure that a pull request only includes the
48     commits related to that bug or feature.
49
50  1. Do your best to have [well-formed commit messages][] for each change.
51     This provides consistency throughout the project, and ensures that commit
52     messages are able to be formatted properly by various git tools.
53
54  1. Finally, push the commits to your fork and submit a [pull request][].
55
56[forking]: https://help.github.com/articles/fork-a-repo
57[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
58[pull request]: https://help.github.com/articles/creating-a-pull-request
trunk/3rdparty/benchmark/CONTRIBUTORS
r0r253077
1# People who have agreed to one of the CLAs and can contribute patches.
2# The AUTHORS file lists the copyright holders; this file
3# lists people.  For example, Google employees are listed here
4# but not in AUTHORS, because Google holds the copyright.
5#
6# Names should be added to this file only after verifying that
7# the individual or the individual's organization has agreed to
8# the appropriate Contributor License Agreement, found here:
9#
10# https://developers.google.com/open-source/cla/individual
11# https://developers.google.com/open-source/cla/corporate
12#
13# The agreement for individuals can be filled out on the web.
14#
15# When adding J Random Contributor's name to this file,
16# either J's name or J's organization's name should be
17# added to the AUTHORS file, depending on whether the
18# individual or corporate CLA was used.
19#
20# Names should be added to this file as:
21#     Name <email address>
22#
23# Please keep the list sorted.
24
25Arne Beer <arne@twobeer.de>
26Chris Kennelly <ckennelly@google.com> <ckennelly@ckennelly.com>
27Christopher Seymour <chris.j.seymour@hotmail.com>
28David Coeurjolly <david.coeurjolly@liris.cnrs.fr>
29Dominic Hamon <dma@stripysock.com>
30Eugene Zhuk <eugene.zhuk@gmail.com>
31Evgeny Safronov <division494@gmail.com>
32Felix Homann <linuxaudio@showlabor.de>
33JianXiong Zhou <zhoujianxiong2@gmail.com>
34Kaito Udagawa <umireon@gmail.com>
35Lei Xu <eddyxu@gmail.com>
36Matt Clarkson <mattyclarkson@gmail.com>
37Oleksandr Sochka <sasha.sochka@gmail.com>
38Pascal Leroy <phl@google.com>
39Paul Redmond <paul.redmond@gmail.com>
40Pierre Phaneuf <pphaneuf@google.com>
41Radoslav Yovchev <radoslav.tm@gmail.com>
42Shuo Chen <chenshuo@chenshuo.com>
43Yusuke Suzuki <utatane.tea@gmail.com>
44Tobias Ulvgård <tobias.ulvgard@dirac.se>
45Zbigniew Skowron <zbychs@gmail.com>
46Dominik Czarnota <dominik.b.czarnota@gmail.com>
trunk/3rdparty/benchmark/LICENSE
r0r253077
1
2                                 Apache License
3                           Version 2.0, January 2004
4                        http://www.apache.org/licenses/
5
6   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
8   1. Definitions.
9
10      "License" shall mean the terms and conditions for use, reproduction,
11      and distribution as defined by Sections 1 through 9 of this document.
12
13      "Licensor" shall mean the copyright owner or entity authorized by
14      the copyright owner that is granting the License.
15
16      "Legal Entity" shall mean the union of the acting entity and all
17      other entities that control, are controlled by, or are under common
18      control with that entity. For the purposes of this definition,
19      "control" means (i) the power, direct or indirect, to cause the
20      direction or management of such entity, whether by contract or
21      otherwise, or (ii) ownership of fifty percent (50%) or more of the
22      outstanding shares, or (iii) beneficial ownership of such entity.
23
24      "You" (or "Your") shall mean an individual or Legal Entity
25      exercising permissions granted by this License.
26
27      "Source" form shall mean the preferred form for making modifications,
28      including but not limited to software source code, documentation
29      source, and configuration files.
30
31      "Object" form shall mean any form resulting from mechanical
32      transformation or translation of a Source form, including but
33      not limited to compiled object code, generated documentation,
34      and conversions to other media types.
35
36      "Work" shall mean the work of authorship, whether in Source or
37      Object form, made available under the License, as indicated by a
38      copyright notice that is included in or attached to the work
39      (an example is provided in the Appendix below).
40
41      "Derivative Works" shall mean any work, whether in Source or Object
42      form, that is based on (or derived from) the Work and for which the
43      editorial revisions, annotations, elaborations, or other modifications
44      represent, as a whole, an original work of authorship. For the purposes
45      of this License, Derivative Works shall not include works that remain
46      separable from, or merely link (or bind by name) to the interfaces of,
47      the Work and Derivative Works thereof.
48
49      "Contribution" shall mean any work of authorship, including
50      the original version of the Work and any modifications or additions
51      to that Work or Derivative Works thereof, that is intentionally
52      submitted to Licensor for inclusion in the Work by the copyright owner
53      or by an individual or Legal Entity authorized to submit on behalf of
54      the copyright owner. For the purposes of this definition, "submitted"
55      means any form of electronic, verbal, or written communication sent
56      to the Licensor or its representatives, including but not limited to
57      communication on electronic mailing lists, source code control systems,
58      and issue tracking systems that are managed by, or on behalf of, the
59      Licensor for the purpose of discussing and improving the Work, but
60      excluding communication that is conspicuously marked or otherwise
61      designated in writing by the copyright owner as "Not a Contribution."
62
63      "Contributor" shall mean Licensor and any individual or Legal Entity
64      on behalf of whom a Contribution has been received by Licensor and
65      subsequently incorporated within the Work.
66
67   2. Grant of Copyright License. Subject to the terms and conditions of
68      this License, each Contributor hereby grants to You a perpetual,
69      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70      copyright license to reproduce, prepare Derivative Works of,
71      publicly display, publicly perform, sublicense, and distribute the
72      Work and such Derivative Works in Source or Object form.
73
74   3. Grant of Patent License. Subject to the terms and conditions of
75      this License, each Contributor hereby grants to You a perpetual,
76      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77      (except as stated in this section) patent license to make, have made,
78      use, offer to sell, sell, import, and otherwise transfer the Work,
79      where such license applies only to those patent claims licensable
80      by such Contributor that are necessarily infringed by their
81      Contribution(s) alone or by combination of their Contribution(s)
82      with the Work to which such Contribution(s) was submitted. If You
83      institute patent litigation against any entity (including a
84      cross-claim or counterclaim in a lawsuit) alleging that the Work
85      or a Contribution incorporated within the Work constitutes direct
86      or contributory patent infringement, then any patent licenses
87      granted to You under this License for that Work shall terminate
88      as of the date such litigation is filed.
89
90   4. Redistribution. You may reproduce and distribute copies of the
91      Work or Derivative Works thereof in any medium, with or without
92      modifications, and in Source or Object form, provided that You
93      meet the following conditions:
94
95      (a) You must give any other recipients of the Work or
96          Derivative Works a copy of this License; and
97
98      (b) You must cause any modified files to carry prominent notices
99          stating that You changed the files; and
100
101      (c) You must retain, in the Source form of any Derivative Works
102          that You distribute, all copyright, patent, trademark, and
103          attribution notices from the Source form of the Work,
104          excluding those notices that do not pertain to any part of
105          the Derivative Works; and
106
107      (d) If the Work includes a "NOTICE" text file as part of its
108          distribution, then any Derivative Works that You distribute must
109          include a readable copy of the attribution notices contained
110          within such NOTICE file, excluding those notices that do not
111          pertain to any part of the Derivative Works, in at least one
112          of the following places: within a NOTICE text file distributed
113          as part of the Derivative Works; within the Source form or
114          documentation, if provided along with the Derivative Works; or,
115          within a display generated by the Derivative Works, if and
116          wherever such third-party notices normally appear. The contents
117          of the NOTICE file are for informational purposes only and
118          do not modify the License. You may add Your own attribution
119          notices within Derivative Works that You distribute, alongside
120          or as an addendum to the NOTICE text from the Work, provided
121          that such additional attribution notices cannot be construed
122          as modifying the License.
123
124      You may add Your own copyright statement to Your modifications and
125      may provide additional or different license terms and conditions
126      for use, reproduction, or distribution of Your modifications, or
127      for any such Derivative Works as a whole, provided Your use,
128      reproduction, and distribution of the Work otherwise complies with
129      the conditions stated in this License.
130
131   5. Submission of Contributions. Unless You explicitly state otherwise,
132      any Contribution intentionally submitted for inclusion in the Work
133      by You to the Licensor shall be under the terms and conditions of
134      this License, without any additional terms or conditions.
135      Notwithstanding the above, nothing herein shall supersede or modify
136      the terms of any separate license agreement you may have executed
137      with Licensor regarding such Contributions.
138
139   6. Trademarks. This License does not grant permission to use the trade
140      names, trademarks, service marks, or product names of the Licensor,
141      except as required for reasonable and customary use in describing the
142      origin of the Work and reproducing the content of the NOTICE file.
143
144   7. Disclaimer of Warranty. Unless required by applicable law or
145      agreed to in writing, Licensor provides the Work (and each
146      Contributor provides its Contributions) on an "AS IS" BASIS,
147      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148      implied, including, without limitation, any warranties or conditions
149      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150      PARTICULAR PURPOSE. You are solely responsible for determining the
151      appropriateness of using or redistributing the Work and assume any
152      risks associated with Your exercise of permissions under this License.
153
154   8. Limitation of Liability. In no event and under no legal theory,
155      whether in tort (including negligence), contract, or otherwise,
156      unless required by applicable law (such as deliberate and grossly
157      negligent acts) or agreed to in writing, shall any Contributor be
158      liable to You for damages, including any direct, indirect, special,
159      incidental, or consequential damages of any character arising as a
160      result of this License or out of the use or inability to use the
161      Work (including but not limited to damages for loss of goodwill,
162      work stoppage, computer failure or malfunction, or any and all
163      other commercial damages or losses), even if such Contributor
164      has been advised of the possibility of such damages.
165
166   9. Accepting Warranty or Additional Liability. While redistributing
167      the Work or Derivative Works thereof, You may choose to offer,
168      and charge a fee for, acceptance of support, warranty, indemnity,
169      or other liability obligations and/or rights consistent with this
170      License. However, in accepting such obligations, You may act only
171      on Your own behalf and on Your sole responsibility, not on behalf
172      of any other Contributor, and only if You agree to indemnify,
173      defend, and hold each Contributor harmless for any liability
174      incurred by, or claims asserted against, such Contributor by reason
175      of your accepting any such warranty or additional liability.
176
177   END OF TERMS AND CONDITIONS
178
179   APPENDIX: How to apply the Apache License to your work.
180
181      To apply the Apache License to your work, attach the following
182      boilerplate notice, with the fields enclosed by brackets "[]"
183      replaced with your own identifying information. (Don't include
184      the brackets!)  The text should be enclosed in the appropriate
185      comment syntax for the file format. We also recommend that a
186      file or class name and description of purpose be included on the
187      same "printed page" as the copyright notice for easier
188      identification within third-party archives.
189
190   Copyright [yyyy] [name of copyright owner]
191
192   Licensed under the Apache License, Version 2.0 (the "License");
193   you may not use this file except in compliance with the License.
194   You may obtain a copy of the License at
195
196       http://www.apache.org/licenses/LICENSE-2.0
197
198   Unless required by applicable law or agreed to in writing, software
199   distributed under the License is distributed on an "AS IS" BASIS,
200   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201   See the License for the specific language governing permissions and
202   limitations under the License.
trunk/3rdparty/benchmark/README.md
r0r253077
1benchmark
2=========
3[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=master)](https://travis-ci.org/google/benchmark)
4[![Build status](https://ci.appveyor.com/api/projects/status/u0qsyp7t1tk7cpxs/branch/master?svg=true)](https://ci.appveyor.com/project/google/benchmark/branch/master)
5[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark)
6
7A library to support the benchmarking of functions, similar to unit-tests.
8
9Discussion group: https://groups.google.com/d/forum/benchmark-discuss
10
11IRC channel: https://freenode.net #googlebenchmark
12
13Example usage
14-------------
15Define a function that executes the code to be measured a
16specified number of times:
17
18```c++
19static void BM_StringCreation(benchmark::State& state) {
20  while (state.KeepRunning())
21    std::string empty_string;
22}
23// Register the function as a benchmark
24BENCHMARK(BM_StringCreation);
25
26// Define another benchmark
27static void BM_StringCopy(benchmark::State& state) {
28  std::string x = "hello";
29  while (state.KeepRunning())
30    std::string copy(x);
31}
32BENCHMARK(BM_StringCopy);
33
34BENCHMARK_MAIN();
35```
36
37Sometimes a family of microbenchmarks can be implemented with
38just one routine that takes an extra argument to specify which
39one of the family of benchmarks to run.  For example, the following
40code defines a family of microbenchmarks for measuring the speed
41of `memcpy()` calls of different lengths:
42
43```c++
44static void BM_memcpy(benchmark::State& state) {
45  char* src = new char[state.range_x()]; char* dst = new char[state.range_x()];
46  memset(src, 'x', state.range_x());
47  while (state.KeepRunning())
48    memcpy(dst, src, state.range_x());
49  state.SetBytesProcessed(int64_t(state.iterations()) *
50                          int64_t(state.range_x()));
51  delete[] src;
52  delete[] dst;
53}
54BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
55```
56
57The preceding code is quite repetitive, and can be replaced with the
58following short-hand.  The following invocation will pick a few
59appropriate arguments in the specified range and will generate a
60microbenchmark for each such argument.
61
62```c++
63BENCHMARK(BM_memcpy)->Range(8, 8<<10);
64```
65
66You might have a microbenchmark that depends on two inputs.  For
67example, the following code defines a family of microbenchmarks for
68measuring the speed of set insertion.
69
70```c++
71static void BM_SetInsert(benchmark::State& state) {
72  while (state.KeepRunning()) {
73    state.PauseTiming();
74    std::set<int> data = ConstructRandomSet(state.range_x());
75    state.ResumeTiming();
76    for (int j = 0; j < state.range_y(); ++j)
77      data.insert(RandomNumber());
78  }
79}
80BENCHMARK(BM_SetInsert)
81    ->ArgPair(1<<10, 1)
82    ->ArgPair(1<<10, 8)
83    ->ArgPair(1<<10, 64)
84    ->ArgPair(1<<10, 512)
85    ->ArgPair(8<<10, 1)
86    ->ArgPair(8<<10, 8)
87    ->ArgPair(8<<10, 64)
88    ->ArgPair(8<<10, 512);
89```
90
91The preceding code is quite repetitive, and can be replaced with
92the following short-hand.  The following macro will pick a few
93appropriate arguments in the product of the two specified ranges
94and will generate a microbenchmark for each such pair.
95
96```c++
97BENCHMARK(BM_SetInsert)->RangePair(1<<10, 8<<10, 1, 512);
98```
99
100For more complex patterns of inputs, passing a custom function
101to Apply allows programmatic specification of an
102arbitrary set of arguments to run the microbenchmark on.
103The following example enumerates a dense range on one parameter,
104and a sparse range on the second.
105
106```c++
107static void CustomArguments(benchmark::internal::Benchmark* b) {
108  for (int i = 0; i <= 10; ++i)
109    for (int j = 32; j <= 1024*1024; j *= 8)
110      b->ArgPair(i, j);
111}
112BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
113```
114
115Templated microbenchmarks work the same way:
116Produce then consume 'size' messages 'iters' times
117Measures throughput in the absence of multiprogramming.
118
119```c++
120template <class Q> int BM_Sequential(benchmark::State& state) {
121  Q q;
122  typename Q::value_type v;
123  while (state.KeepRunning()) {
124    for (int i = state.range_x(); i--; )
125      q.push(v);
126    for (int e = state.range_x(); e--; )
127      q.Wait(&v);
128  }
129  // actually messages, not bytes:
130  state.SetBytesProcessed(
131      static_cast<int64_t>(state.iterations())*state.range_x());
132}
133BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
134```
135
136Three macros are provided for adding benchmark templates.
137
138```c++
139#if __cplusplus >= 201103L // C++11 and greater.
140#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters.
141#else // C++ < C++11
142#define BENCHMARK_TEMPLATE(func, arg1)
143#endif
144#define BENCHMARK_TEMPLATE1(func, arg1)
145#define BENCHMARK_TEMPLATE2(func, arg1, arg2)
146```
147
148In a multithreaded test (benchmark invoked by multiple threads simultaneously),
149it is guaranteed that none of the threads will start until all have called
150KeepRunning, and all will have finished before KeepRunning returns false. As
151such, any global setup or teardown you want to do can be
152wrapped in a check against the thread index:
153
154```c++
155static void BM_MultiThreaded(benchmark::State& state) {
156  if (state.thread_index == 0) {
157    // Setup code here.
158  }
159  while (state.KeepRunning()) {
160    // Run the test as normal.
161  }
162  if (state.thread_index == 0) {
163    // Teardown code here.
164  }
165}
166BENCHMARK(BM_MultiThreaded)->Threads(2);
167```
168
169If the benchmarked code itself uses threads and you want to compare it to
170single-threaded code, you may want to use real-time ("wallclock") measurements
171for latency comparisons:
172
173```c++
174BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();
175```
176
177Without `UseRealTime`, CPU time is used by default.
178
179To prevent a value or expression from being optimized away by the compiler
180the `benchmark::DoNotOptimize(...)` function can be used.
181
182```c++
183static void BM_test(benchmark::State& state) {
184  while (state.KeepRunning()) {
185      int x = 0;
186      for (int i=0; i < 64; ++i) {
187        benchmark::DoNotOptimize(x += i);
188      }
189  }
190}
191```
192
193Benchmark Fixtures
194------------------
195Fixture tests are created by
196first defining a type that derives from ::benchmark::Fixture and then
197creating/registering the tests using the following macros:
198
199* `BENCHMARK_F(ClassName, Method)`
200* `BENCHMARK_DEFINE_F(ClassName, Method)`
201* `BENCHMARK_REGISTER_F(ClassName, Method)`
202
203For Example:
204
205```c++
206class MyFixture : public benchmark::Fixture {};
207
208BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {
209   while (st.KeepRunning()) {
210     ...
211  }
212}
213
214BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {
215   while (st.KeepRunning()) {
216     ...
217  }
218}
219/* BarTest is NOT registered */
220BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);
221/* BarTest is now registered */
222```
223
224Output Formats
225--------------
226The library supports multiple output formats. Use the
227`--benchmark_format=<tabular|json>` flag to set the format type. `tabular` is
228the default format.
229
230The Tabular format is intended to be a human readable format. By default
231the format generates color output. Context is output on stderr and the
232tabular data on stdout. Example tabular output looks like:
233```
234Benchmark                               Time(ns)    CPU(ns) Iterations
235----------------------------------------------------------------------
236BM_SetInsert/1024/1                        28928      29349      23853  133.097kB/s   33.2742k items/s
237BM_SetInsert/1024/8                        32065      32913      21375  949.487kB/s   237.372k items/s
238BM_SetInsert/1024/10                       33157      33648      21431  1.13369MB/s   290.225k items/s
239```
240
241The JSON format outputs human readable json split into two top level attributes.
242The `context` attribute contains information about the run in general, including
243information about the CPU and the date.
244The `benchmarks` attribute contains a list of ever benchmark run. Example json
245output looks like:
246```
247{
248  "context": {
249    "date": "2015/03/17-18:40:25",
250    "num_cpus": 40,
251    "mhz_per_cpu": 2801,
252    "cpu_scaling_enabled": false,
253    "build_type": "debug"
254  },
255  "benchmarks": [
256    {
257      "name": "BM_SetInsert/1024/1",
258      "iterations": 94877,
259      "real_time": 29275,
260      "cpu_time": 29836,
261      "bytes_per_second": 134066,
262      "items_per_second": 33516
263    },
264    {
265      "name": "BM_SetInsert/1024/8",
266      "iterations": 21609,
267      "real_time": 32317,
268      "cpu_time": 32429,
269      "bytes_per_second": 986770,
270      "items_per_second": 246693
271    },
272    {
273      "name": "BM_SetInsert/1024/10",
274      "iterations": 21393,
275      "real_time": 32724,
276      "cpu_time": 33355,
277      "bytes_per_second": 1199226,
278      "items_per_second": 299807
279    }
280  ]
281}
282```
283
284The CSV format outputs comma-separated values. The `context` is output on stderr
285and the CSV itself on stdout. Example CSV output looks like:
286```
287name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label
288"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942,
289"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115,
290"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,
291```
292
293Linking against the library
294---------------------------
295When using gcc, it is necessary to link against pthread to avoid runtime exceptions. This is due to how gcc implements std::thread. See [issue #67](https://github.com/google/benchmark/issues/67) for more details.
trunk/3rdparty/benchmark/appveyor.yml
r0r253077
1version: '{build}'
2
3configuration:
4  - Static Debug
5  - Static Release
6#  - Shared Debug
7#  - Shared Release
8
9platform:
10  - x86
11  - x64
12
13environment:
14  matrix:
15    - compiler: gcc-4.9.2-posix
16#    - compiler: gcc-4.8.4-posix
17#    - compiler: msvc-12-seh
18
19install:
20  # derive some extra information
21  - for /f "tokens=1-2" %%a in ("%configuration%") do (@set "linkage=%%a")
22  - for /f "tokens=1-2" %%a in ("%configuration%") do (@set "variant=%%b")
23  - if "%linkage%"=="Shared" (set shared=YES) else (set shared=NO)
24  - for /f "tokens=1-3 delims=-" %%a in ("%compiler%") do (@set "compiler_name=%%a")
25  - for /f "tokens=1-3 delims=-" %%a in ("%compiler%") do (@set "compiler_version=%%b")
26  - for /f "tokens=1-3 delims=-" %%a in ("%compiler%") do (@set "compiler_threading=%%c")
27  - if "%platform%"=="x64" (set arch=x86_64)
28  - if "%platform%"=="x86" (set arch=i686)
29  # download the specific version of MinGW
30  - if "%compiler_name%"=="gcc" (for /f %%a in ('python mingw.py --quiet --version "%compiler_version%" --arch "%arch%" --threading "%compiler_threading%" --location "C:\mingw-builds"') do @set "compiler_path=%%a")
31
32before_build:
33  # Set up mingw commands
34  - if "%compiler_name%"=="gcc" (set "generator=MinGW Makefiles")
35  - if "%compiler_name%"=="gcc" (set "build=mingw32-make -j4")
36  - if "%compiler_name%"=="gcc" (set "test=mingw32-make CTEST_OUTPUT_ON_FAILURE=1 test")
37  # msvc specific commands
38  # TODO :)
39  # add the compiler path if needed
40  - if not "%compiler_path%"=="" (set "PATH=%PATH%;%compiler_path%")
41  # git bash conflicts with MinGW makefiles
42  - if "%generator%"=="MinGW Makefiles" (set "PATH=%PATH:C:\Program Files (x86)\Git\bin=%")
43
44build_script:
45  - cmake -G "%generator%" "-DCMAKE_BUILD_TYPE=%variant%" "-DBUILD_SHARED_LIBS=%shared%"
46  - cmd /c "%build%"
47
48test_script:
49  - cmd /c "%test%"
50
51matrix:
52  fast_finish: true
53
54cache:
55  - C:\mingw-builds
trunk/3rdparty/benchmark/cmake/AddCXXCompilerFlag.cmake
r0r253077
1# - Adds a compiler flag if it is supported by the compiler
2#
3# This function checks that the supplied compiler flag is supported and then
4# adds it to the corresponding compiler flags
5#
6#  add_cxx_compiler_flag(<FLAG> [<VARIANT>])
7#
8# - Example
9#
10# include(AddCXXCompilerFlag)
11# add_cxx_compiler_flag(-Wall)
12# add_cxx_compiler_flag(-no-strict-aliasing RELEASE)
13# Requires CMake 2.6+
14
15if(__add_cxx_compiler_flag)
16  return()
17endif()
18set(__add_cxx_compiler_flag INCLUDED)
19
20include(CheckCXXCompilerFlag)
21
22function(add_cxx_compiler_flag FLAG)
23  string(TOUPPER "HAVE_CXX_FLAG_${FLAG}" SANITIZED_FLAG)
24  string(REPLACE "+" "X" SANITIZED_FLAG ${SANITIZED_FLAG})
25  string(REGEX REPLACE "[^A-Za-z_0-9]" "_" SANITIZED_FLAG ${SANITIZED_FLAG})
26  string(REGEX REPLACE "_+" "_" SANITIZED_FLAG ${SANITIZED_FLAG})
27  set(CMAKE_REQUIRED_FLAGS "${FLAG}")
28  check_cxx_compiler_flag("" ${SANITIZED_FLAG})
29  if(${SANITIZED_FLAG})
30    set(VARIANT ${ARGV1})
31    if(ARGV1)
32      string(TOUPPER "_${VARIANT}" VARIANT)
33    endif()
34    set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE)
35  endif()
36endfunction()
37
trunk/3rdparty/benchmark/cmake/CXXFeatureCheck.cmake
r0r253077
1# - Compile and run code to check for C++ features
2#
3# This functions compiles a source file under the `cmake` folder
4# and adds the corresponding `HAVE_[FILENAME]` flag to the CMake
5# environment
6#
7#  cxx_feature_check(<FLAG> [<VARIANT>])
8#
9# - Example
10#
11# include(CXXFeatureCheck)
12# cxx_feature_check(STD_REGEX)
13# Requires CMake 2.6+
14
15if(__cxx_feature_check)
16  return()
17endif()
18set(__cxx_feature_check INCLUDED)
19
20function(cxx_feature_check FILE)
21  string(TOLOWER ${FILE} FILE)
22  string(TOUPPER ${FILE} VAR)
23  string(TOUPPER "HAVE_${VAR}" FEATURE)
24  message("-- Performing Test ${FEATURE}")
25  try_run(RUN_${FEATURE} COMPILE_${FEATURE}
26          ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp)
27  if(RUN_${FEATURE} EQUAL 0)
28    message("-- Performing Test ${FEATURE} -- success")
29    set(HAVE_${VAR} 1 PARENT_SCOPE)
30    add_definitions(-DHAVE_${VAR})
31  else()
32    if(NOT COMPILE_${FEATURE})
33      message("-- Performing Test ${FEATURE} -- failed to compile")
34    else()
35      message("-- Performing Test ${FEATURE} -- compiled but failed to run")
36    endif()
37  endif()
38endfunction()
39
trunk/3rdparty/benchmark/cmake/GetGitVersion.cmake
r0r253077
1# - Returns a version string from Git tags
2#
3# This function inspects the annotated git tags for the project and returns a string
4# into a CMake variable
5#
6#  get_git_version(<var>)
7#
8# - Example
9#
10# include(GetGitVersion)
11# get_git_version(GIT_VERSION)
12#
13# Requires CMake 2.8.11+
14find_package(Git)
15
16if(__get_git_version)
17  return()
18endif()
19set(__get_git_version INCLUDED)
20
21function(get_git_version var)
22  if(GIT_EXECUTABLE)
23      execute_process(COMMAND ${GIT_EXECUTABLE} describe --match "v[0-9]*.[0-9]*.[0-9]*" --abbrev=8
24          RESULT_VARIABLE status
25          OUTPUT_VARIABLE GIT_VERSION
26          ERROR_QUIET)
27      if(${status})
28          set(GIT_VERSION "v0.0.0")
29      else()
30          string(STRIP ${GIT_VERSION} GIT_VERSION)
31          string(REGEX REPLACE "-[0-9]+-g" "-" GIT_VERSION ${GIT_VERSION})
32      endif()
33
34      # Work out if the repository is dirty
35      execute_process(COMMAND ${GIT_EXECUTABLE} update-index -q --refresh
36          OUTPUT_QUIET
37          ERROR_QUIET)
38      execute_process(COMMAND ${GIT_EXECUTABLE} diff-index --name-only HEAD --
39          OUTPUT_VARIABLE GIT_DIFF_INDEX
40          ERROR_QUIET)
41      string(COMPARE NOTEQUAL "${GIT_DIFF_INDEX}" "" GIT_DIRTY)
42      if (${GIT_DIRTY})
43          set(GIT_VERSION "${GIT_VERSION}-dirty")
44      endif()
45  else()
46      set(GIT_VERSION "v0.0.0")
47  endif()
48
49  message("-- git Version: ${GIT_VERSION}")
50  set(${var} ${GIT_VERSION} PARENT_SCOPE)
51endfunction()
trunk/3rdparty/benchmark/cmake/gnu_posix_regex.cpp
r0r253077
1#include <gnuregex.h>
2#include <string>
3int main() {
4  std::string str = "test0159";
5  regex_t re;
6  int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB);
7  if (ec != 0) {
8    return ec;
9  }
10  return regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0;
11}
12
trunk/3rdparty/benchmark/cmake/posix_regex.cpp
r0r253077
1#include <regex.h>
2#include <string>
3int main() {
4  std::string str = "test0159";
5  regex_t re;
6  int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB);
7  if (ec != 0) {
8    return ec;
9  }
10  return regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0;
11}
12
trunk/3rdparty/benchmark/cmake/std_regex.cpp
r0r253077
1#include <regex>
2#include <string>
3int main() {
4  const std::string str = "test0159";
5  std::regex re;
6  re = std::regex("^[a-z]+[0-9]+$",
7       std::regex_constants::extended | std::regex_constants::nosubs);
8  return std::regex_search(str, re) ? 0 : -1;
9}
10
trunk/3rdparty/benchmark/cmake/steady_clock.cpp
r0r253077
1#include <chrono>
2
3int main() {
4    typedef std::chrono::steady_clock Clock;
5    Clock::time_point tp = Clock::now();
6    ((void)tp);
7}
trunk/3rdparty/benchmark/cmake/thread_safety_attributes.cpp
r0r253077
1#define HAVE_THREAD_SAFETY_ATTRIBUTES
2#include "../src/mutex.h"
3
4int main() {}
trunk/3rdparty/benchmark/include/benchmark/benchmark.h
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#ifndef BENCHMARK_BENCHMARK_H_
15#define BENCHMARK_BENCHMARK_H_
16
17#include "macros.h"
18#include "benchmark_api.h"
19#include "reporter.h"
20
21#endif // BENCHMARK_BENCHMARK_H_
trunk/3rdparty/benchmark/include/benchmark/benchmark_api.h
r0r253077
1// Support for registering benchmarks for functions.
2
3/* Example usage:
4// Define a function that executes the code to be measured a
5// specified number of times:
6static void BM_StringCreation(benchmark::State& state) {
7  while (state.KeepRunning())
8    std::string empty_string;
9}
10
11// Register the function as a benchmark
12BENCHMARK(BM_StringCreation);
13
14// Define another benchmark
15static void BM_StringCopy(benchmark::State& state) {
16  std::string x = "hello";
17  while (state.KeepRunning())
18    std::string copy(x);
19}
20BENCHMARK(BM_StringCopy);
21
22// Augment the main() program to invoke benchmarks if specified
23// via the --benchmarks command line flag.  E.g.,
24//       my_unittest --benchmark_filter=all
25//       my_unittest --benchmark_filter=BM_StringCreation
26//       my_unittest --benchmark_filter=String
27//       my_unittest --benchmark_filter='Copy|Creation'
28int main(int argc, char** argv) {
29  benchmark::Initialize(&argc, argv);
30  benchmark::RunSpecifiedBenchmarks();
31  return 0;
32}
33
34// Sometimes a family of microbenchmarks can be implemented with
35// just one routine that takes an extra argument to specify which
36// one of the family of benchmarks to run.  For example, the following
37// code defines a family of microbenchmarks for measuring the speed
38// of memcpy() calls of different lengths:
39
40static void BM_memcpy(benchmark::State& state) {
41  char* src = new char[state.range_x()]; char* dst = new char[state.range_x()];
42  memset(src, 'x', state.range_x());
43  while (state.KeepRunning())
44    memcpy(dst, src, state.range_x());
45  state.SetBytesProcessed(int64_t(state.iterations()) *
46                          int64_t(state.range_x()));
47  delete[] src; delete[] dst;
48}
49BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
50
51// The preceding code is quite repetitive, and can be replaced with the
52// following short-hand.  The following invocation will pick a few
53// appropriate arguments in the specified range and will generate a
54// microbenchmark for each such argument.
55BENCHMARK(BM_memcpy)->Range(8, 8<<10);
56
57// You might have a microbenchmark that depends on two inputs.  For
58// example, the following code defines a family of microbenchmarks for
59// measuring the speed of set insertion.
60static void BM_SetInsert(benchmark::State& state) {
61  while (state.KeepRunning()) {
62    state.PauseTiming();
63    set<int> data = ConstructRandomSet(state.range_x());
64    state.ResumeTiming();
65    for (int j = 0; j < state.range_y(); ++j)
66      data.insert(RandomNumber());
67  }
68}
69BENCHMARK(BM_SetInsert)
70   ->ArgPair(1<<10, 1)
71   ->ArgPair(1<<10, 8)
72   ->ArgPair(1<<10, 64)
73   ->ArgPair(1<<10, 512)
74   ->ArgPair(8<<10, 1)
75   ->ArgPair(8<<10, 8)
76   ->ArgPair(8<<10, 64)
77   ->ArgPair(8<<10, 512);
78
79// The preceding code is quite repetitive, and can be replaced with
80// the following short-hand.  The following macro will pick a few
81// appropriate arguments in the product of the two specified ranges
82// and will generate a microbenchmark for each such pair.
83BENCHMARK(BM_SetInsert)->RangePair(1<<10, 8<<10, 1, 512);
84
85// For more complex patterns of inputs, passing a custom function
86// to Apply allows programmatic specification of an
87// arbitrary set of arguments to run the microbenchmark on.
88// The following example enumerates a dense range on
89// one parameter, and a sparse range on the second.
90static void CustomArguments(benchmark::internal::Benchmark* b) {
91  for (int i = 0; i <= 10; ++i)
92    for (int j = 32; j <= 1024*1024; j *= 8)
93      b->ArgPair(i, j);
94}
95BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
96
97// Templated microbenchmarks work the same way:
98// Produce then consume 'size' messages 'iters' times
99// Measures throughput in the absence of multiprogramming.
100template <class Q> int BM_Sequential(benchmark::State& state) {
101  Q q;
102  typename Q::value_type v;
103  while (state.KeepRunning()) {
104    for (int i = state.range_x(); i--; )
105      q.push(v);
106    for (int e = state.range_x(); e--; )
107      q.Wait(&v);
108  }
109  // actually messages, not bytes:
110  state.SetBytesProcessed(
111      static_cast<int64_t>(state.iterations())*state.range_x());
112}
113BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
114
115Use `Benchmark::MinTime(double t)` to set the minimum time used to run the
116benchmark. This option overrides the `benchmark_min_time` flag.
117
118void BM_test(benchmark::State& state) {
119 ... body ...
120}
121BENCHMARK(BM_test)->MinTime(2.0); // Run for at least 2 seconds.
122
123In a multithreaded test, it is guaranteed that none of the threads will start
124until all have called KeepRunning, and all will have finished before KeepRunning
125returns false. As such, any global setup or teardown you want to do can be
126wrapped in a check against the thread index:
127
128static void BM_MultiThreaded(benchmark::State& state) {
129  if (state.thread_index == 0) {
130    // Setup code here.
131  }
132  while (state.KeepRunning()) {
133    // Run the test as normal.
134  }
135  if (state.thread_index == 0) {
136    // Teardown code here.
137  }
138}
139BENCHMARK(BM_MultiThreaded)->Threads(4);
140*/
141
142#ifndef BENCHMARK_BENCHMARK_API_H_
143#define BENCHMARK_BENCHMARK_API_H_
144
145#include <assert.h>
146#include <stddef.h>
147#include <stdint.h>
148
149#include "macros.h"
150
151namespace benchmark {
152class BenchmarkReporter;
153
154void Initialize(int* argc, char** argv);
155
156// Otherwise, run all benchmarks specified by the --benchmark_filter flag,
157// and exit after running the benchmarks.
158void RunSpecifiedBenchmarks();
159void RunSpecifiedBenchmarks(BenchmarkReporter* reporter);
160
161// If this routine is called, peak memory allocation past this point in the
162// benchmark is reported at the end of the benchmark report line. (It is
163// computed by running the benchmark once with a single iteration and a memory
164// tracer.)
165// TODO(dominic)
166// void MemoryUsage();
167
168namespace internal {
169class Benchmark;
170class BenchmarkImp;
171class BenchmarkFamilies;
172
173template <class T> struct Voider {
174    typedef void type;
175};
176
177template <class T, class = void>
178struct EnableIfString {};
179
180template <class T>
181struct EnableIfString<T, typename Voider<typename T::basic_string>::type> {
182    typedef int type;
183};
184
185void UseCharPointer(char const volatile*);
186
187// Take ownership of the pointer and register the benchmark. Return the
188// registered benchmark.
189Benchmark* RegisterBenchmarkInternal(Benchmark*);
190
191} // end namespace internal
192
193
194// The DoNotOptimize(...) function can be used to prevent a value or
195// expression from being optimized away by the compiler. This function is
196// intented to add little to no overhead.
197// See: http://stackoverflow.com/questions/28287064
198#if defined(__clang__) && defined(__GNUC__)
199// TODO(ericwf): Clang has a bug where it tries to always use a register
200// even if value must be stored in memory. This causes codegen to fail.
201// To work around this we remove the "r" modifier so the operand is always
202// loaded into memory.
203template <class Tp>
204inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
205    asm volatile("" : "+m" (const_cast<Tp&>(value)));
206}
207#elif defined(__GNUC__)
208template <class Tp>
209inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
210    asm volatile("" : "+rm" (const_cast<Tp&>(value)));
211}
212#else
213template <class Tp>
214inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
215    internal::UseCharPointer(&reinterpret_cast<char const volatile&>(value));
216}
217#endif
218
219
220// State is passed to a running Benchmark and contains state for the
221// benchmark to use.
222class State {
223public:
224  State(size_t max_iters, bool has_x, int x, bool has_y, int y, int thread_i);
225
226  // Returns true iff the benchmark should continue through another iteration.
227  // NOTE: A benchmark may not return from the test until KeepRunning() has
228  // returned false.
229  bool KeepRunning() {
230    if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) {
231        ResumeTiming();
232        started_ = true;
233    }
234    bool const res = total_iterations_++ < max_iterations;
235    if (BENCHMARK_BUILTIN_EXPECT(!res, false)) {
236        assert(started_);
237        PauseTiming();
238        // Total iterations now is one greater than max iterations. Fix this.
239        total_iterations_ = max_iterations;
240    }
241    return res;
242  }
243
244  // REQUIRES: timer is running
245  // Stop the benchmark timer.  If not called, the timer will be
246  // automatically stopped after KeepRunning() returns false for the first time.
247  //
248  // For threaded benchmarks the PauseTiming() function acts
249  // like a barrier.  I.e., the ith call by a particular thread to this
250  // function will block until all threads have made their ith call.
251  // The timer will stop when the last thread has called this function.
252  //
253  // NOTE: PauseTiming()/ResumeTiming() are relatively
254  // heavyweight, and so their use should generally be avoided
255  // within each benchmark iteration, if possible.
256  void PauseTiming();
257
258  // REQUIRES: timer is not running
259  // Start the benchmark timer.  The timer is NOT running on entrance to the
260  // benchmark function. It begins running after the first call to KeepRunning()
261  //
262  // For threaded benchmarks the ResumeTiming() function acts
263  // like a barrier.  I.e., the ith call by a particular thread to this
264  // function will block until all threads have made their ith call.
265  // The timer will start when the last thread has called this function.
266  //
267  // NOTE: PauseTiming()/ResumeTiming() are relatively
268  // heavyweight, and so their use should generally be avoided
269  // within each benchmark iteration, if possible.
270  void ResumeTiming();
271
272  // Set the number of bytes processed by the current benchmark
273  // execution.  This routine is typically called once at the end of a
274  // throughput oriented benchmark.  If this routine is called with a
275  // value > 0, the report is printed in MB/sec instead of nanoseconds
276  // per iteration.
277  //
278  // REQUIRES: a benchmark has exited its KeepRunning loop.
279  BENCHMARK_ALWAYS_INLINE
280  void SetBytesProcessed(size_t bytes) {
281    bytes_processed_ = bytes;
282  }
283
284  BENCHMARK_ALWAYS_INLINE
285  size_t bytes_processed() const {
286    return bytes_processed_;
287  }
288
289  // If this routine is called with items > 0, then an items/s
290  // label is printed on the benchmark report line for the currently
291  // executing benchmark. It is typically called at the end of a processing
292  // benchmark where a processing items/second output is desired.
293  //
294  // REQUIRES: a benchmark has exited its KeepRunning loop.
295  BENCHMARK_ALWAYS_INLINE
296  void SetItemsProcessed(size_t items) {
297    items_processed_ = items;
298  }
299
300  BENCHMARK_ALWAYS_INLINE
301  size_t items_processed() const {
302    return items_processed_;
303  }
304
305  // If this routine is called, the specified label is printed at the
306  // end of the benchmark report line for the currently executing
307  // benchmark.  Example:
308  //  static void BM_Compress(int iters) {
309  //    ...
310  //    double compress = input_size / output_size;
311  //    benchmark::SetLabel(StringPrintf("compress:%.1f%%", 100.0*compression));
312  //  }
313  // Produces output that looks like:
314  //  BM_Compress   50         50   14115038  compress:27.3%
315  //
316  // REQUIRES: a benchmark has exited its KeepRunning loop.
317  void SetLabel(const char* label);
318
319  // Allow the use of std::string without actually including <string>.
320  // This function does not participate in overload resolution unless StringType
321  // has the nested typename `basic_string`. This typename should be provided
322  // as an injected class name in the case of std::string.
323  template <class StringType>
324  void SetLabel(StringType const & str,
325                typename internal::EnableIfString<StringType>::type = 1) {
326    this->SetLabel(str.c_str());
327  }
328
329  // Range arguments for this run. CHECKs if the argument has been set.
330  BENCHMARK_ALWAYS_INLINE
331  int range_x() const {
332    assert(has_range_x_);
333    ((void)has_range_x_); // Prevent unused warning.
334    return range_x_;
335  }
336
337  BENCHMARK_ALWAYS_INLINE
338  int range_y() const {
339    assert(has_range_y_);
340    ((void)has_range_y_); // Prevent unused warning.
341    return range_y_;
342  }
343
344  BENCHMARK_ALWAYS_INLINE
345  size_t iterations() const { return total_iterations_; }
346
347private:
348  bool started_;
349  size_t total_iterations_;
350
351  bool has_range_x_;
352  int range_x_;
353
354  bool has_range_y_;
355  int range_y_;
356
357  size_t bytes_processed_;
358  size_t items_processed_;
359
360public:
361  const int thread_index;
362  const size_t max_iterations;
363
364private:
365  BENCHMARK_DISALLOW_COPY_AND_ASSIGN(State);
366};
367
368namespace internal {
369
370typedef void(Function)(State&);
371
372// ------------------------------------------------------
373// Benchmark registration object.  The BENCHMARK() macro expands
374// into an internal::Benchmark* object.  Various methods can
375// be called on this object to change the properties of the benchmark.
376// Each method returns "this" so that multiple method calls can
377// chained into one expression.
378class Benchmark {
379public:
380  virtual ~Benchmark();
381
382  // Note: the following methods all return "this" so that multiple
383  // method calls can be chained together in one expression.
384
385  // Run this benchmark once with "x" as the extra argument passed
386  // to the function.
387  // REQUIRES: The function passed to the constructor must accept an arg1.
388  Benchmark* Arg(int x);
389
390  // Run this benchmark once for a number of values picked from the
391  // range [start..limit].  (start and limit are always picked.)
392  // REQUIRES: The function passed to the constructor must accept an arg1.
393  Benchmark* Range(int start, int limit);
394
395  // Run this benchmark once for every value in the range [start..limit]
396  // REQUIRES: The function passed to the constructor must accept an arg1.
397  Benchmark* DenseRange(int start, int limit);
398
399  // Run this benchmark once with "x,y" as the extra arguments passed
400  // to the function.
401  // REQUIRES: The function passed to the constructor must accept arg1,arg2.
402  Benchmark* ArgPair(int x, int y);
403
404  // Pick a set of values A from the range [lo1..hi1] and a set
405  // of values B from the range [lo2..hi2].  Run the benchmark for
406  // every pair of values in the cartesian product of A and B
407  // (i.e., for all combinations of the values in A and B).
408  // REQUIRES: The function passed to the constructor must accept arg1,arg2.
409  Benchmark* RangePair(int lo1, int hi1, int lo2, int hi2);
410
411  // Pass this benchmark object to *func, which can customize
412  // the benchmark by calling various methods like Arg, ArgPair,
413  // Threads, etc.
414  Benchmark* Apply(void (*func)(Benchmark* benchmark));
415
416  // Set the minimum amount of time to use when running this benchmark. This
417  // option overrides the `benchmark_min_time` flag.
418  Benchmark* MinTime(double t);
419
420  // If a particular benchmark is I/O bound, runs multiple threads internally or
421  // if for some reason CPU timings are not representative, call this method. If
422  // called, the elapsed time will be used to control how many iterations are
423  // run, and in the printing of items/second or MB/seconds values.  If not
424  // called, the cpu time used by the benchmark will be used.
425  Benchmark* UseRealTime();
426
427  // Support for running multiple copies of the same benchmark concurrently
428  // in multiple threads.  This may be useful when measuring the scaling
429  // of some piece of code.
430
431  // Run one instance of this benchmark concurrently in t threads.
432  Benchmark* Threads(int t);
433
434  // Pick a set of values T from [min_threads,max_threads].
435  // min_threads and max_threads are always included in T.  Run this
436  // benchmark once for each value in T.  The benchmark run for a
437  // particular value t consists of t threads running the benchmark
438  // function concurrently.  For example, consider:
439  //    BENCHMARK(Foo)->ThreadRange(1,16);
440  // This will run the following benchmarks:
441  //    Foo in 1 thread
442  //    Foo in 2 threads
443  //    Foo in 4 threads
444  //    Foo in 8 threads
445  //    Foo in 16 threads
446  Benchmark* ThreadRange(int min_threads, int max_threads);
447
448  // Equivalent to ThreadRange(NumCPUs(), NumCPUs())
449  Benchmark* ThreadPerCpu();
450
451  virtual void Run(State& state) = 0;
452
453  // Used inside the benchmark implementation
454  struct Instance;
455
456protected:
457  explicit Benchmark(const char* name);
458  Benchmark(Benchmark const&);
459  void SetName(const char* name);
460
461private:
462  friend class BenchmarkFamilies;
463  BenchmarkImp* imp_;
464
465  Benchmark& operator=(Benchmark const&);
466};
467
468// The class used to hold all Benchmarks created from static function.
469// (ie those created using the BENCHMARK(...) macros.
470class FunctionBenchmark : public Benchmark {
471public:
472    FunctionBenchmark(const char* name, Function* func)
473        : Benchmark(name), func_(func)
474    {}
475
476    virtual void Run(State& st);
477private:
478    Function* func_;
479};
480
481}  // end namespace internal
482
483// The base class for all fixture tests.
484class Fixture: public internal::Benchmark {
485public:
486    Fixture() : internal::Benchmark("") {}
487
488    virtual void Run(State& st) {
489      this->SetUp();
490      this->BenchmarkCase(st);
491      this->TearDown();
492    }
493
494    virtual void SetUp() {}
495    virtual void TearDown() {}
496
497protected:
498    virtual void BenchmarkCase(State&) = 0;
499};
500
501}  // end namespace benchmark
502
503
504// ------------------------------------------------------
505// Macro to register benchmarks
506
507// Check that __COUNTER__ is defined and that __COUNTER__ increases by 1
508// every time it is expanded. X + 1 == X + 0 is used in case X is defined to be
509// empty. If X is empty the expression becomes (+1 == +0).
510#if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0)
511#define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__
512#else
513#define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__
514#endif
515
516// Helpers for generating unique variable names
517#define BENCHMARK_PRIVATE_NAME(n) \
518    BENCHMARK_PRIVATE_CONCAT(_benchmark_, BENCHMARK_PRIVATE_UNIQUE_ID, n)
519#define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c)
520#define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c
521
522#define BENCHMARK_PRIVATE_DECLARE(n)       \
523  static ::benchmark::internal::Benchmark* \
524  BENCHMARK_PRIVATE_NAME(n) BENCHMARK_UNUSED
525
526#define BENCHMARK(n) \
527    BENCHMARK_PRIVATE_DECLARE(n) =                               \
528        (::benchmark::internal::RegisterBenchmarkInternal(       \
529            new ::benchmark::internal::FunctionBenchmark(#n, n)))
530
531// Old-style macros
532#define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a))
533#define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->ArgPair((a1), (a2))
534#define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi))
535#define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \
536  BENCHMARK(n)->RangePair((l1), (h1), (l2), (h2))
537
538// This will register a benchmark for a templatized function.  For example:
539//
540// template<int arg>
541// void BM_Foo(int iters);
542//
543// BENCHMARK_TEMPLATE(BM_Foo, 1);
544//
545// will register BM_Foo<1> as a benchmark.
546#define BENCHMARK_TEMPLATE1(n, a) \
547  BENCHMARK_PRIVATE_DECLARE(n) =  \
548      (::benchmark::internal::RegisterBenchmarkInternal( \
549        new ::benchmark::internal::FunctionBenchmark(#n "<" #a ">", n<a>)))
550
551#define BENCHMARK_TEMPLATE2(n, a, b)                     \
552  BENCHMARK_PRIVATE_DECLARE(n) =                         \
553      (::benchmark::internal::RegisterBenchmarkInternal( \
554        new ::benchmark::internal::FunctionBenchmark(    \
555            #n "<" #a "," #b ">", n<a, b>)))
556
557#if __cplusplus >= 201103L
558#define BENCHMARK_TEMPLATE(n, ...)           \
559  BENCHMARK_PRIVATE_DECLARE(n) =             \
560      (::benchmark::internal::RegisterBenchmarkInternal( \
561        new ::benchmark::internal::FunctionBenchmark( \
562        #n "<" #__VA_ARGS__ ">", n<__VA_ARGS__>)))
563#else
564#define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a)
565#endif
566
567
568#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method)      \
569class BaseClass##_##Method##_Benchmark : public BaseClass { \
570public:                                                     \
571    BaseClass##_##Method##_Benchmark() : BaseClass() {      \
572        this->SetName(#BaseClass "/" #Method);}             \
573protected:                                                  \
574    virtual void BenchmarkCase(::benchmark::State&);        \
575};
576
577#define BENCHMARK_DEFINE_F(BaseClass, Method) \
578    BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
579    void BaseClass##_##Method##_Benchmark::BenchmarkCase
580
581#define BENCHMARK_REGISTER_F(BaseClass, Method) \
582    BENCHMARK_PRIVATE_REGISTER_F(BaseClass##_##Method##_Benchmark)
583
584#define BENCHMARK_PRIVATE_REGISTER_F(TestName) \
585    BENCHMARK_PRIVATE_DECLARE(TestName) = \
586        (::benchmark::internal::RegisterBenchmarkInternal(new TestName()))
587
588// This macro will define and register a benchmark within a fixture class.
589#define BENCHMARK_F(BaseClass, Method) \
590    BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
591    BENCHMARK_REGISTER_F(BaseClass, Method); \
592    void BaseClass##_##Method##_Benchmark::BenchmarkCase
593
594
595// Helper macro to create a main routine in a test that runs the benchmarks
596#define BENCHMARK_MAIN()                   \
597  int main(int argc, char** argv) {        \
598    ::benchmark::Initialize(&argc, argv);  \
599    ::benchmark::RunSpecifiedBenchmarks(); \
600  }
601
602#endif  // BENCHMARK_BENCHMARK_API_H_
trunk/3rdparty/benchmark/include/benchmark/macros.h
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#ifndef BENCHMARK_MACROS_H_
15#define BENCHMARK_MACROS_H_
16
17#if __cplusplus < 201103L
18# define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName)  \
19    TypeName(const TypeName&);                         \
20    TypeName& operator=(const TypeName&)
21#else
22# define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName)  \
23    TypeName(const TypeName&) = delete;                \
24    TypeName& operator=(const TypeName&) = delete
25#endif
26
27#if defined(__GNUC__)
28# define BENCHMARK_UNUSED __attribute__((unused))
29# define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline))
30# define BENCHMARK_NOEXCEPT noexcept
31#elif defined(_MSC_VER) && !defined(__clang__)
32# define BENCHMARK_UNUSED
33# define BENCHMARK_ALWAYS_INLINE __forceinline
34# define BENCHMARK_NOEXCEPT
35# define __func__ __FUNCTION__
36#else
37# define BENCHMARK_UNUSED
38# define BENCHMARK_ALWAYS_INLINE
39# define BENCHMARK_NOEXCEPT
40#endif
41
42#if defined(__GNUC__)
43# define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y)
44#else
45# define BENCHMARK_BUILTIN_EXPECT(x, y) x
46#endif
47
48#endif  // BENCHMARK_MACROS_H_
trunk/3rdparty/benchmark/include/benchmark/reporter.h
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#ifndef BENCHMARK_REPORTER_H_
15#define BENCHMARK_REPORTER_H_
16
17#include <string>
18#include <utility>
19#include <vector>
20
21#include "benchmark_api.h" // For forward declaration of BenchmarkReporter
22
23namespace benchmark {
24
25// Interface for custom benchmark result printers.
26// By default, benchmark reports are printed to stdout. However an application
27// can control the destination of the reports by calling
28// RunSpecifiedBenchmarks and passing it a custom reporter object.
29// The reporter object must implement the following interface.
30class BenchmarkReporter {
31 public:
32  struct Context {
33    int num_cpus;
34    double mhz_per_cpu;
35    bool cpu_scaling_enabled;
36
37    // The number of chars in the longest benchmark name.
38    size_t name_field_width;
39  };
40
41  struct Run {
42    Run() :
43      iterations(1),
44      real_accumulated_time(0),
45      cpu_accumulated_time(0),
46      bytes_per_second(0),
47      items_per_second(0),
48      max_heapbytes_used(0) {}
49
50    std::string benchmark_name;
51    std::string report_label;  // Empty if not set by benchmark.
52    int64_t iterations;
53    double real_accumulated_time;
54    double cpu_accumulated_time;
55
56    // Zero if not set by benchmark.
57    double bytes_per_second;
58    double items_per_second;
59
60    // This is set to 0.0 if memory tracing is not enabled.
61    double max_heapbytes_used;
62  };
63
64  // Called once for every suite of benchmarks run.
65  // The parameter "context" contains information that the
66  // reporter may wish to use when generating its report, for example the
67  // platform under which the benchmarks are running. The benchmark run is
68  // never started if this function returns false, allowing the reporter
69  // to skip runs based on the context information.
70  virtual bool ReportContext(const Context& context) = 0;
71
72  // Called once for each group of benchmark runs, gives information about
73  // cpu-time and heap memory usage during the benchmark run.
74  // Note that all the grouped benchmark runs should refer to the same
75  // benchmark, thus have the same name.
76  virtual void ReportRuns(const std::vector<Run>& report) = 0;
77
78  // Called once and only once after ever group of benchmarks is run and
79  // reported.
80  virtual void Finalize();
81
82  virtual ~BenchmarkReporter();
83protected:
84    static void ComputeStats(std::vector<Run> const& reports, Run* mean, Run* stddev);
85};
86
87// Simple reporter that outputs benchmark data to the console. This is the
88// default reporter used by RunSpecifiedBenchmarks().
89class ConsoleReporter : public BenchmarkReporter {
90 public:
91  virtual bool ReportContext(const Context& context);
92  virtual void ReportRuns(const std::vector<Run>& reports);
93protected:
94  virtual void PrintRunData(const Run& report);
95
96  size_t name_field_width_;
97};
98
99class JSONReporter : public BenchmarkReporter {
100public:
101  JSONReporter() : first_report_(true) {}
102  virtual bool ReportContext(const Context& context);
103  virtual void ReportRuns(const std::vector<Run>& reports);
104  virtual void Finalize();
105
106private:
107  void PrintRunData(const Run& report);
108
109  bool first_report_;
110};
111
112class CSVReporter : public BenchmarkReporter {
113public:
114  virtual bool ReportContext(const Context& context);
115  virtual void ReportRuns(const std::vector<Run>& reports);
116
117private:
118  void PrintRunData(const Run& report);
119};
120
121} // end namespace benchmark
122#endif // BENCHMARK_REPORTER_H_
trunk/3rdparty/benchmark/mingw.py
r0r253077
1#! /usr/bin/env python
2# encoding: utf-8
3
4import argparse
5import errno
6import logging
7import os
8import platform
9import re
10import sys
11import subprocess
12import tempfile
13
14try:
15    import winreg
16except ImportError:
17    import _winreg as winreg
18try:
19    import urllib.request as request
20except ImportError:
21    import urllib as request
22try:
23    import urllib.parse as parse
24except ImportError:
25    import urlparse as parse
26
27class EmptyLogger(object):
28    '''
29    Provides an implementation that performs no logging
30    '''
31    def debug(self, *k, **kw):
32        pass
33    def info(self, *k, **kw):
34        pass
35    def warn(self, *k, **kw):
36        pass
37    def error(self, *k, **kw):
38        pass
39    def critical(self, *k, **kw):
40        pass
41    def setLevel(self, *k, **kw):
42        pass
43
44urls = (
45    'http://downloads.sourceforge.net/project/mingw-w64/Toolchains%20'
46        'targetting%20Win32/Personal%20Builds/mingw-builds/installer/'
47        'repository.txt',
48    'http://downloads.sourceforge.net/project/mingwbuilds/host-windows/'
49        'repository.txt'
50)
51'''
52A list of mingw-build repositories
53'''
54
55def repository(urls = urls, log = EmptyLogger()):
56    '''
57    Downloads and parse mingw-build repository files and parses them
58    '''
59    log.info('getting mingw-builds repository')
60    versions = {}
61    re_sourceforge = re.compile(r'http://sourceforge.net/projects/([^/]+)/files')
62    re_sub = r'http://downloads.sourceforge.net/project/\1'
63    for url in urls:
64        log.debug(' - requesting: %s', url)
65        socket = request.urlopen(url)
66        repo = socket.read()
67        if not isinstance(repo, str):
68            repo = repo.decode();
69        socket.close()
70        for entry in repo.split('\n')[:-1]:
71            value = entry.split('|')
72            version = tuple([int(n) for n in value[0].strip().split('.')])
73            version = versions.setdefault(version, {})
74            arch = value[1].strip()
75            if arch == 'x32':
76                arch = 'i686'
77            elif arch == 'x64':
78                arch = 'x86_64'
79            arch = version.setdefault(arch, {})
80            threading = arch.setdefault(value[2].strip(), {})
81            exceptions = threading.setdefault(value[3].strip(), {})
82            revision = exceptions.setdefault(int(value[4].strip()[3:]),
83                re_sourceforge.sub(re_sub, value[5].strip()))
84    return versions
85
86def find_in_path(file, path=None):
87    '''
88    Attempts to find an executable in the path
89    '''
90    if platform.system() == 'Windows':
91        file += '.exe'
92    if path is None:
93        path = os.environ.get('PATH', '')
94    if type(path) is type(''):
95        path = path.split(os.pathsep)
96    return list(filter(os.path.exists,
97        map(lambda dir, file=file: os.path.join(dir, file), path)))
98
99def find_7zip(log = EmptyLogger()):
100    '''
101    Attempts to find 7zip for unpacking the mingw-build archives
102    '''
103    log.info('finding 7zip')
104    path = find_in_path('7z')
105    if not path:
106        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\7-Zip')
107        path, _ = winreg.QueryValueEx(key, 'Path')
108        path = [os.path.join(path, '7z.exe')]
109    log.debug('found \'%s\'', path[0])
110    return path[0]
111
112find_7zip()
113
114def unpack(archive, location, log = EmptyLogger()):
115    '''
116    Unpacks a mingw-builds archive
117    '''
118    sevenzip = find_7zip(log)
119    log.info('unpacking %s', os.path.basename(archive))
120    cmd = [sevenzip, 'x', archive, '-o' + location, '-y']
121    log.debug(' - %r', cmd)
122    with open(os.devnull, 'w') as devnull:
123        subprocess.check_call(cmd, stdout = devnull)
124
125def download(url, location, log = EmptyLogger()):
126    '''
127    Downloads and unpacks a mingw-builds archive
128    '''
129    log.info('downloading MinGW')
130    log.debug(' - url: %s', url)
131    log.debug(' - location: %s', location)
132
133    re_content = re.compile(r'attachment;[ \t]*filename=(")?([^"]*)(")?[\r\n]*')
134
135    stream = request.urlopen(url)
136    try:
137        content = stream.getheader('Content-Disposition') or ''
138    except AttributeError:
139        content = stream.headers.getheader('Content-Disposition') or ''
140    matches = re_content.match(content)
141    if matches:
142        filename = matches.group(2)
143    else:
144        parsed = parse.urlparse(stream.geturl())
145        filename = os.path.basename(parsed.path)
146
147    try:
148        os.makedirs(location)
149    except OSError as e:
150        if e.errno == errno.EEXIST and os.path.isdir(location):
151            pass
152        else:
153            raise
154
155    archive = os.path.join(location, filename)
156    with open(archive, 'wb') as out:
157        while True:
158            buf = stream.read(1024)
159            if not buf:
160                break
161            out.write(buf)
162    unpack(archive, location, log = log)
163    os.remove(archive)
164
165    possible = os.path.join(location, 'mingw64')
166    if not os.path.exists(possible):
167        possible = os.path.join(location, 'mingw32')
168        if not os.path.exists(possible):
169            raise ValueError('Failed to find unpacked MinGW: ' + possible)
170    return possible
171
172def root(location = None, arch = None, version = None, threading = None,
173        exceptions = None, revision = None, log = EmptyLogger()):
174    '''
175    Returns the root folder of a specific version of the mingw-builds variant
176    of gcc. Will download the compiler if needed
177    '''
178
179    # Get the repository if we don't have all the information
180    if not (arch and version and threading and exceptions and revision):
181        versions = repository(log = log)
182
183    # Determine some defaults
184    version = version or max(versions.keys())
185    if not arch:
186        arch = platform.machine().lower()
187        if arch == 'x86':
188            arch = 'i686'
189        elif arch == 'amd64':
190            arch = 'x86_64'
191    if not threading:
192        keys = versions[version][arch].keys()
193        if 'posix' in keys:
194            threading = 'posix'
195        elif 'win32' in keys:
196            threading = 'win32'
197        else:
198            threading = keys[0]
199    if not exceptions:
200        keys = versions[version][arch][threading].keys()
201        if 'seh' in keys:
202            exceptions = 'seh'
203        elif 'sjlj' in keys:
204            exceptions = 'sjlj'
205        else:
206            exceptions = keys[0]
207    if revision == None:
208        revision = max(versions[version][arch][threading][exceptions].keys())
209    if not location:
210        location = os.path.join(tempfile.gettempdir(), 'mingw-builds')
211
212    # Get the download url
213    url = versions[version][arch][threading][exceptions][revision]
214
215    # Tell the user whatzzup
216    log.info('finding MinGW %s', '.'.join(str(v) for v in version))
217    log.debug(' - arch: %s', arch)
218    log.debug(' - threading: %s', threading)
219    log.debug(' - exceptions: %s', exceptions)
220    log.debug(' - revision: %s', revision)
221    log.debug(' - url: %s', url)
222
223    # Store each specific revision differently
224    slug = '{version}-{arch}-{threading}-{exceptions}-rev{revision}'
225    slug = slug.format(
226        version = '.'.join(str(v) for v in version),
227        arch = arch,
228        threading = threading,
229        exceptions = exceptions,
230        revision = revision
231    )
232    if arch == 'x86_64':
233        root_dir = os.path.join(location, slug, 'mingw64')
234    elif arch == 'i686':
235        root_dir = os.path.join(location, slug, 'mingw32')
236    else:
237        raise ValueError('Unknown MinGW arch: ' + arch)
238
239    # Download if needed
240    if not os.path.exists(root_dir):
241        downloaded = download(url, os.path.join(location, slug), log = log)
242        if downloaded != root_dir:
243            raise ValueError('The location of mingw did not match\n%s\n%s'
244                % (downloaded, root_dir))
245
246    return root_dir
247
248def str2ver(string):
249    '''
250    Converts a version string into a tuple
251    '''
252    try:
253        version = tuple(int(v) for v in string.split('.'))
254        if len(version) is not 3:
255            raise ValueError()
256    except ValueError:
257        raise argparse.ArgumentTypeError(
258            'please provide a three digit version string')
259    return version
260
261def main():
262    '''
263    Invoked when the script is run directly by the python interpreter
264    '''
265    parser = argparse.ArgumentParser(
266        description = 'Downloads a specific version of MinGW',
267        formatter_class = argparse.ArgumentDefaultsHelpFormatter
268    )
269    parser.add_argument('--location',
270        help = 'the location to download the compiler to',
271        default = os.path.join(tempfile.gettempdir(), 'mingw-builds'))
272    parser.add_argument('--arch', required = True, choices = ['i686', 'x86_64'],
273        help = 'the target MinGW architecture string')
274    parser.add_argument('--version', type = str2ver,
275        help = 'the version of GCC to download')
276    parser.add_argument('--threading', choices = ['posix', 'win32'],
277        help = 'the threading type of the compiler')
278    parser.add_argument('--exceptions', choices = ['sjlj', 'seh', 'dwarf'],
279        help = 'the method to throw exceptions')
280    parser.add_argument('--revision', type=int,
281        help = 'the revision of the MinGW release')
282    group = parser.add_mutually_exclusive_group()
283    group.add_argument('-v', '--verbose', action='store_true',
284        help='increase the script output verbosity')
285    group.add_argument('-q', '--quiet', action='store_true',
286        help='only print errors and warning')
287    args = parser.parse_args()
288
289    # Create the logger
290    logger = logging.getLogger('mingw')
291    handler = logging.StreamHandler()
292    formatter = logging.Formatter('%(message)s')
293    handler.setFormatter(formatter)
294    logger.addHandler(handler)
295    logger.setLevel(logging.INFO)
296    if args.quiet:
297        logger.setLevel(logging.WARN)
298    if args.verbose:
299        logger.setLevel(logging.DEBUG)
300
301    # Get MinGW
302    root_dir = root(location = args.location, arch = args.arch,
303        version = args.version, threading = args.threading,
304        exceptions = args.exceptions, revision = args.revision,
305        log = logger)
306
307    sys.stdout.write('%s\n' % os.path.join(root_dir, 'bin'))
308
309if __name__ == '__main__':
310    try:
311        main()
312    except IOError as e:
313        sys.stderr.write('IO error: %s\n' % e)
314        sys.exit(1)
315    except OSError as e:
316        sys.stderr.write('OS error: %s\n' % e)
317        sys.exit(1)
318    except KeyboardInterrupt as e:
319        sys.stderr.write('Killed\n')
320        sys.exit(1)
trunk/3rdparty/benchmark/src/CMakeLists.txt
r0r253077
1# Allow the source files to find headers in src/
2include_directories(${PROJECT_SOURCE_DIR}/src)
3
4# Define the source files
5set(SOURCE_FILES "benchmark.cc" "colorprint.cc" "commandlineflags.cc"
6                 "console_reporter.cc" "csv_reporter.cc" "json_reporter.cc"
7                 "log.cc" "reporter.cc" "sleep.cc" "string_util.cc"
8                 "sysinfo.cc" "walltime.cc")
9# Determine the correct regular expression engine to use
10if(HAVE_STD_REGEX)
11  set(RE_FILES "re_std.cc")
12elseif(HAVE_GNU_POSIX_REGEX)
13  set(RE_FILES "re_posix.cc")
14elseif(HAVE_POSIX_REGEX)
15  set(RE_FILES "re_posix.cc")
16else()
17  message(FATAL_ERROR "Failed to determine the source files for the regular expression backend")
18endif()
19
20add_library(benchmark ${SOURCE_FILES} ${RE_FILES})
21
22
23set_target_properties(benchmark PROPERTIES
24  OUTPUT_NAME "benchmark"
25  VERSION ${GENERIC_LIB_VERSION}
26  SOVERSION ${GENERIC_LIB_SOVERSION}
27)
28
29# Link threads.
30target_link_libraries(benchmark ${CMAKE_THREAD_LIBS_INIT})
31
32# We need extra libraries on Windows
33if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
34  target_link_libraries(benchmark Shlwapi)
35endif()
36
37# Expose public API
38target_include_directories(benchmark PUBLIC ${PROJECT_SOURCE_DIR}/include)
39
40# Install target (will install the library to specified CMAKE_INSTALL_PREFIX variable)
41install(
42  TARGETS benchmark
43  ARCHIVE DESTINATION lib
44  LIBRARY DESTINATION lib
45  RUNTIME DESTINATION bin
46  COMPONENT library)
47
48install(
49  DIRECTORY "${PROJECT_SOURCE_DIR}/include/benchmark"
50  DESTINATION include
51  FILES_MATCHING PATTERN "*.*h")
trunk/3rdparty/benchmark/src/arraysize.h
r0r253077
1#ifndef BENCHMARK_ARRAYSIZE_H_
2#define BENCHMARK_ARRAYSIZE_H_
3
4#include "internal_macros.h"
5
6namespace benchmark {
7namespace internal {
8// The arraysize(arr) macro returns the # of elements in an array arr.
9// The expression is a compile-time constant, and therefore can be
10// used in defining new arrays, for example.  If you use arraysize on
11// a pointer by mistake, you will get a compile-time error.
12//
13
14
15// This template function declaration is used in defining arraysize.
16// Note that the function doesn't need an implementation, as we only
17// use its type.
18template <typename T, size_t N>
19char (&ArraySizeHelper(T (&array)[N]))[N];
20
21// That gcc wants both of these prototypes seems mysterious. VC, for
22// its part, can't decide which to use (another mystery). Matching of
23// template overloads: the final frontier.
24#ifndef COMPILER_MSVC
25template <typename T, size_t N>
26char (&ArraySizeHelper(const T (&array)[N]))[N];
27#endif
28
29#define arraysize(array) (sizeof(::benchmark::internal::ArraySizeHelper(array)))
30
31} // end namespace internal
32} // end namespace benchmark
33
34#endif // BENCHMARK_ARRAYSIZE_H_
trunk/3rdparty/benchmark/src/benchmark.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "benchmark/benchmark.h"
16#include "internal_macros.h"
17
18#ifndef BENCHMARK_OS_WINDOWS
19#include <sys/time.h>
20#include <sys/resource.h>
21#include <unistd.h>
22#endif
23
24#include <cstdlib>
25#include <cstring>
26#include <cstdio>
27#include <algorithm>
28#include <atomic>
29#include <condition_variable>
30#include <iostream>
31#include <memory>
32#include <thread>
33
34#include "check.h"
35#include "commandlineflags.h"
36#include "log.h"
37#include "mutex.h"
38#include "re.h"
39#include "stat.h"
40#include "string_util.h"
41#include "sysinfo.h"
42#include "walltime.h"
43
44DEFINE_bool(benchmark_list_tests, false,
45            "Print a list of benchmarks. This option overrides all other "
46            "options.");
47
48DEFINE_string(benchmark_filter, ".",
49              "A regular expression that specifies the set of benchmarks "
50              "to execute.  If this flag is empty, no benchmarks are run.  "
51              "If this flag is the string \"all\", all benchmarks linked "
52              "into the process are run.");
53
54DEFINE_double(benchmark_min_time, 0.5,
55              "Minimum number of seconds we should run benchmark before "
56              "results are considered significant.  For cpu-time based "
57              "tests, this is the lower bound on the total cpu time "
58              "used by all threads that make up the test.  For real-time "
59              "based tests, this is the lower bound on the elapsed time "
60              "of the benchmark execution, regardless of number of "
61              "threads.");
62
63DEFINE_int32(benchmark_repetitions, 1,
64             "The number of runs of each benchmark. If greater than 1, the "
65             "mean and standard deviation of the runs will be reported.");
66
67DEFINE_string(benchmark_format, "tabular",
68              "The format to use for console output. Valid values are "
69              "'tabular', 'json', or 'csv'.");
70
71DEFINE_bool(color_print, true, "Enables colorized logging.");
72
73DEFINE_int32(v, 0, "The level of verbose logging to output");
74
75
76namespace benchmark {
77
78namespace internal {
79
80void UseCharPointer(char const volatile*) {}
81
82// NOTE: This is a dummy "mutex" type used to denote the actual mutex
83// returned by GetBenchmarkLock(). This is only used to placate the thread
84// safety warnings by giving the return of GetBenchmarkLock() a name.
85struct CAPABILITY("mutex") BenchmarkLockType {};
86BenchmarkLockType BenchmarkLockVar;
87
88} // end namespace internal
89
90inline Mutex& RETURN_CAPABILITY(::benchmark::internal::BenchmarkLockVar)
91GetBenchmarkLock()
92{
93  static Mutex lock;
94  return lock;
95}
96
97namespace {
98
99bool IsZero(double n) {
100    return std::abs(n) < std::numeric_limits<double>::epsilon();
101}
102
103// For non-dense Range, intermediate values are powers of kRangeMultiplier.
104static const int kRangeMultiplier = 8;
105static const size_t kMaxIterations = 1000000000;
106
107bool running_benchmark = false;
108
109// Global variable so that a benchmark can cause a little extra printing
110std::string* GetReportLabel() {
111    static std::string label GUARDED_BY(GetBenchmarkLock());
112    return &label;
113}
114
115// TODO(ericwf): support MallocCounter.
116//static benchmark::MallocCounter *benchmark_mc;
117
118struct ThreadStats {
119    ThreadStats() : bytes_processed(0), items_processed(0) {}
120    int64_t bytes_processed;
121    int64_t items_processed;
122};
123
124// Timer management class
125class TimerManager {
126 public:
127  TimerManager(int num_threads, Notification* done)
128      : num_threads_(num_threads),
129        done_(done),
130        running_(false),
131        real_time_used_(0),
132        cpu_time_used_(0),
133        num_finalized_(0),
134        phase_number_(0),
135        entered_(0) {
136  }
137
138  // Called by each thread
139  void StartTimer() EXCLUDES(lock_) {
140    bool last_thread = false;
141    {
142      MutexLock ml(lock_);
143      last_thread = Barrier(ml);
144      if (last_thread) {
145        CHECK(!running_) << "Called StartTimer when timer is already running";
146        running_ = true;
147        start_real_time_ = walltime::Now();
148        start_cpu_time_ = MyCPUUsage() + ChildrenCPUUsage();
149       }
150     }
151     if (last_thread) {
152       phase_condition_.notify_all();
153     }
154  }
155
156  // Called by each thread
157  void StopTimer() EXCLUDES(lock_) {
158    bool last_thread = false;
159    {
160      MutexLock ml(lock_);
161      last_thread = Barrier(ml);
162      if (last_thread) {
163        CHECK(running_) << "Called StopTimer when timer is already stopped";
164        InternalStop();
165      }
166    }
167    if (last_thread) {
168      phase_condition_.notify_all();
169    }
170  }
171
172  // Called by each thread
173  void Finalize() EXCLUDES(lock_) {
174    MutexLock l(lock_);
175    num_finalized_++;
176    if (num_finalized_ == num_threads_) {
177      CHECK(!running_) <<
178        "The timer should be stopped before the timer is finalized";
179      done_->Notify();
180    }
181  }
182
183  // REQUIRES: timer is not running
184  double real_time_used() EXCLUDES(lock_) {
185    MutexLock l(lock_);
186    CHECK(!running_);
187    return real_time_used_;
188  }
189
190  // REQUIRES: timer is not running
191  double cpu_time_used() EXCLUDES(lock_) {
192    MutexLock l(lock_);
193    CHECK(!running_);
194    return cpu_time_used_;
195  }
196
197 private:
198  Mutex lock_;
199  Condition phase_condition_;
200  int num_threads_;
201  Notification* done_;
202
203  bool running_;                // Is the timer running
204  double start_real_time_;      // If running_
205  double start_cpu_time_;       // If running_
206
207  // Accumulated time so far (does not contain current slice if running_)
208  double real_time_used_;
209  double cpu_time_used_;
210
211  // How many threads have called Finalize()
212  int num_finalized_;
213
214  // State for barrier management
215  int phase_number_;
216  int entered_;         // Number of threads that have entered this barrier
217
218  void InternalStop() REQUIRES(lock_) {
219    CHECK(running_);
220    running_ = false;
221    real_time_used_ += walltime::Now() - start_real_time_;
222    cpu_time_used_ += ((MyCPUUsage() + ChildrenCPUUsage())
223                       - start_cpu_time_);
224  }
225
226  // Enter the barrier and wait until all other threads have also
227  // entered the barrier.  Returns iff this is the last thread to
228  // enter the barrier.
229  bool Barrier(MutexLock& ml) REQUIRES(lock_) {
230    CHECK_LT(entered_, num_threads_);
231    entered_++;
232    if (entered_ < num_threads_) {
233      // Wait for all threads to enter
234      int phase_number_cp = phase_number_;
235      auto cb = [this, phase_number_cp]() {
236        return this->phase_number_ > phase_number_cp;
237      };
238      phase_condition_.wait(ml.native_handle(), cb);
239      return false;  // I was not the last one
240    } else {
241      // Last thread has reached the barrier
242      phase_number_++;
243      entered_ = 0;
244      return true;
245    }
246  }
247};
248
249// TimerManager for current run.
250static std::unique_ptr<TimerManager> timer_manager = nullptr;
251
252} // end namespace
253
254namespace internal {
255
256// Information kept per benchmark we may want to run
257struct Benchmark::Instance {
258  std::string    name;
259  Benchmark*     benchmark;
260  bool           has_arg1;
261  int            arg1;
262  bool           has_arg2;
263  int            arg2;
264  bool           use_real_time;
265  double         min_time;
266  int            threads;    // Number of concurrent threads to use
267  bool           multithreaded;  // Is benchmark multi-threaded?
268};
269
270// Class for managing registered benchmarks.  Note that each registered
271// benchmark identifies a family of related benchmarks to run.
272class BenchmarkFamilies {
273 public:
274  static BenchmarkFamilies* GetInstance();
275
276  // Registers a benchmark family and returns the index assigned to it.
277  size_t AddBenchmark(std::unique_ptr<Benchmark> family);
278
279  // Extract the list of benchmark instances that match the specified
280  // regular expression.
281  bool FindBenchmarks(const std::string& re,
282                      std::vector<Benchmark::Instance>* benchmarks);
283 private:
284  BenchmarkFamilies() {}
285
286  std::vector<std::unique_ptr<Benchmark>> families_;
287  Mutex mutex_;
288};
289
290
291class BenchmarkImp {
292public:
293  explicit BenchmarkImp(const char* name);
294  ~BenchmarkImp();
295
296  void Arg(int x);
297  void Range(int start, int limit);
298  void DenseRange(int start, int limit);
299  void ArgPair(int start, int limit);
300  void RangePair(int lo1, int hi1, int lo2, int hi2);
301  void MinTime(double n);
302  void UseRealTime();
303  void Threads(int t);
304  void ThreadRange(int min_threads, int max_threads);
305  void ThreadPerCpu();
306  void SetName(const char* name);
307
308  static void AddRange(std::vector<int>* dst, int lo, int hi, int mult);
309
310private:
311  friend class BenchmarkFamilies;
312
313  std::string name_;
314  int arg_count_;
315  std::vector< std::pair<int, int> > args_;  // Args for all benchmark runs
316  double min_time_;
317  bool use_real_time_;
318  std::vector<int> thread_counts_;
319
320  BenchmarkImp& operator=(BenchmarkImp const&);
321};
322
323BenchmarkFamilies* BenchmarkFamilies::GetInstance() {
324  static BenchmarkFamilies instance;
325  return &instance;
326}
327
328
329size_t BenchmarkFamilies::AddBenchmark(std::unique_ptr<Benchmark> family) {
330  MutexLock l(mutex_);
331  size_t index = families_.size();
332  families_.push_back(std::move(family));
333  return index;
334}
335
336bool BenchmarkFamilies::FindBenchmarks(
337    const std::string& spec,
338    std::vector<Benchmark::Instance>* benchmarks) {
339  // Make regular expression out of command-line flag
340  std::string error_msg;
341  Regex re;
342  if (!re.Init(spec, &error_msg)) {
343    std::cerr << "Could not compile benchmark re: " << error_msg << std::endl;
344    return false;
345  }
346
347  // Special list of thread counts to use when none are specified
348  std::vector<int> one_thread;
349  one_thread.push_back(1);
350
351  MutexLock l(mutex_);
352  for (std::unique_ptr<Benchmark>& bench_family : families_) {
353    // Family was deleted or benchmark doesn't match
354    if (!bench_family) continue;
355    BenchmarkImp* family = bench_family->imp_;
356
357    if (family->arg_count_ == -1) {
358      family->arg_count_ = 0;
359      family->args_.emplace_back(-1, -1);
360    }
361    for (auto const& args : family->args_) {
362      const std::vector<int>* thread_counts =
363        (family->thread_counts_.empty()
364         ? &one_thread
365         : &family->thread_counts_);
366      for (int num_threads : *thread_counts) {
367
368        Benchmark::Instance instance;
369        instance.name = family->name_;
370        instance.benchmark = bench_family.get();
371        instance.has_arg1 = family->arg_count_ >= 1;
372        instance.arg1 = args.first;
373        instance.has_arg2 = family->arg_count_ == 2;
374        instance.arg2 = args.second;
375        instance.min_time = family->min_time_;
376        instance.use_real_time = family->use_real_time_;
377        instance.threads = num_threads;
378        instance.multithreaded = !(family->thread_counts_.empty());
379
380        // Add arguments to instance name
381        if (family->arg_count_ >= 1) {
382          AppendHumanReadable(instance.arg1, &instance.name);
383        }
384        if (family->arg_count_ >= 2) {
385          AppendHumanReadable(instance.arg2, &instance.name);
386        }
387        if (!IsZero(family->min_time_)) {
388          instance.name +=  StringPrintF("/min_time:%0.3f",  family->min_time_);
389        }
390        if (family->use_real_time_) {
391          instance.name +=  "/real_time";
392        }
393
394        // Add the number of threads used to the name
395        if (!family->thread_counts_.empty()) {
396          instance.name += StringPrintF("/threads:%d", instance.threads);
397        }
398
399        if (re.Match(instance.name)) {
400          benchmarks->push_back(instance);
401        }
402      }
403    }
404  }
405  return true;
406}
407
408BenchmarkImp::BenchmarkImp(const char* name)
409    : name_(name), arg_count_(-1),
410      min_time_(0.0), use_real_time_(false) {
411}
412
413BenchmarkImp::~BenchmarkImp() {
414}
415
416void BenchmarkImp::Arg(int x) {
417  CHECK(arg_count_ == -1 || arg_count_ == 1);
418  arg_count_ = 1;
419  args_.emplace_back(x, -1);
420}
421
422void BenchmarkImp::Range(int start, int limit) {
423  CHECK(arg_count_ == -1 || arg_count_ == 1);
424  arg_count_ = 1;
425  std::vector<int> arglist;
426  AddRange(&arglist, start, limit, kRangeMultiplier);
427
428  for (int i : arglist) {
429    args_.emplace_back(i, -1);
430  }
431}
432
433void BenchmarkImp::DenseRange(int start, int limit) {
434  CHECK(arg_count_ == -1 || arg_count_ == 1);
435  arg_count_ = 1;
436  CHECK_GE(start, 0);
437  CHECK_LE(start, limit);
438  for (int arg = start; arg <= limit; arg++) {
439    args_.emplace_back(arg, -1);
440  }
441}
442
443void BenchmarkImp::ArgPair(int x, int y) {
444  CHECK(arg_count_ == -1 || arg_count_ == 2);
445  arg_count_ = 2;
446  args_.emplace_back(x, y);
447}
448
449void BenchmarkImp::RangePair(int lo1, int hi1, int lo2, int hi2) {
450  CHECK(arg_count_ == -1 || arg_count_ == 2);
451  arg_count_ = 2;
452  std::vector<int> arglist1, arglist2;
453  AddRange(&arglist1, lo1, hi1, kRangeMultiplier);
454  AddRange(&arglist2, lo2, hi2, kRangeMultiplier);
455
456  for (int i : arglist1) {
457    for (int j : arglist2) {
458      args_.emplace_back(i, j);
459    }
460  }
461}
462
463void BenchmarkImp::MinTime(double t) {
464  CHECK(t > 0.0);
465  min_time_ = t;
466}
467
468void BenchmarkImp::UseRealTime() {
469  use_real_time_ = true;
470}
471
472void BenchmarkImp::Threads(int t) {
473  CHECK_GT(t, 0);
474  thread_counts_.push_back(t);
475}
476
477void BenchmarkImp::ThreadRange(int min_threads, int max_threads) {
478  CHECK_GT(min_threads, 0);
479  CHECK_GE(max_threads, min_threads);
480
481  AddRange(&thread_counts_, min_threads, max_threads, 2);
482}
483
484void BenchmarkImp::ThreadPerCpu() {
485  static int num_cpus = NumCPUs();
486  thread_counts_.push_back(num_cpus);
487}
488
489void BenchmarkImp::SetName(const char* name) {
490  name_ = name;
491}
492
493void BenchmarkImp::AddRange(std::vector<int>* dst, int lo, int hi, int mult) {
494  CHECK_GE(lo, 0);
495  CHECK_GE(hi, lo);
496
497  // Add "lo"
498  dst->push_back(lo);
499
500  static const int kint32max = std::numeric_limits<int32_t>::max();
501
502  // Now space out the benchmarks in multiples of "mult"
503  for (int32_t i = 1; i < kint32max/mult; i *= mult) {
504    if (i >= hi) break;
505    if (i > lo) {
506      dst->push_back(i);
507    }
508  }
509  // Add "hi" (if different from "lo")
510  if (hi != lo) {
511    dst->push_back(hi);
512  }
513}
514
515Benchmark::Benchmark(const char* name)
516    : imp_(new BenchmarkImp(name))
517{
518}
519
520Benchmark::~Benchmark()  {
521  delete imp_;
522}
523
524Benchmark::Benchmark(Benchmark const& other)
525  : imp_(new BenchmarkImp(*other.imp_))
526{
527}
528
529Benchmark* Benchmark::Arg(int x) {
530  imp_->Arg(x);
531  return this;
532}
533
534Benchmark* Benchmark::Range(int start, int limit) {
535  imp_->Range(start, limit);
536  return this;
537}
538
539Benchmark* Benchmark::DenseRange(int start, int limit) {
540  imp_->DenseRange(start, limit);
541  return this;
542}
543
544Benchmark* Benchmark::ArgPair(int x, int y) {
545  imp_->ArgPair(x, y);
546  return this;
547}
548
549Benchmark* Benchmark::RangePair(int lo1, int hi1, int lo2, int hi2) {
550  imp_->RangePair(lo1, hi1, lo2, hi2);
551  return this;
552}
553
554Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) {
555  custom_arguments(this);
556  return this;
557}
558
559Benchmark* Benchmark::MinTime(double t) {
560  imp_->MinTime(t);
561  return this;
562}
563
564Benchmark* Benchmark::UseRealTime() {
565  imp_->UseRealTime();
566  return this;
567}
568
569Benchmark* Benchmark::Threads(int t) {
570  imp_->Threads(t);
571  return this;
572}
573
574Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) {
575  imp_->ThreadRange(min_threads, max_threads);
576  return this;
577}
578
579Benchmark* Benchmark::ThreadPerCpu() {
580  imp_->ThreadPerCpu();
581  return this;
582}
583
584void Benchmark::SetName(const char* name) {
585  imp_->SetName(name);
586}
587
588void FunctionBenchmark::Run(State& st) {
589  func_(st);
590}
591
592} // end namespace internal
593
594namespace {
595
596
597// Execute one thread of benchmark b for the specified number of iterations.
598// Adds the stats collected for the thread into *total.
599void RunInThread(const benchmark::internal::Benchmark::Instance* b,
600                 size_t iters, int thread_id,
601                 ThreadStats* total) EXCLUDES(GetBenchmarkLock()) {
602  State st(iters, b->has_arg1, b->arg1, b->has_arg2, b->arg2, thread_id);
603  b->benchmark->Run(st);
604  CHECK(st.iterations() == st.max_iterations) <<
605    "Benchmark returned before State::KeepRunning() returned false!";
606  {
607    MutexLock l(GetBenchmarkLock());
608    total->bytes_processed += st.bytes_processed();
609    total->items_processed += st.items_processed();
610  }
611
612  timer_manager->Finalize();
613}
614
615void RunBenchmark(const benchmark::internal::Benchmark::Instance& b,
616                  BenchmarkReporter* br) EXCLUDES(GetBenchmarkLock()) {
617  size_t iters = 1;
618
619  std::vector<BenchmarkReporter::Run> reports;
620
621  std::vector<std::thread> pool;
622  if (b.multithreaded)
623    pool.resize(b.threads);
624
625  for (int i = 0; i < FLAGS_benchmark_repetitions; i++) {
626    std::string mem;
627    for (;;) {
628      // Try benchmark
629      VLOG(2) << "Running " << b.name << " for " << iters << "\n";
630
631      {
632        MutexLock l(GetBenchmarkLock());
633        GetReportLabel()->clear();
634      }
635
636      Notification done;
637      timer_manager = std::unique_ptr<TimerManager>(new TimerManager(b.threads, &done));
638
639      ThreadStats total;
640      running_benchmark = true;
641      if (b.multithreaded) {
642        // If this is out first iteration of the while(true) loop then the
643        // threads haven't been started and can't be joined. Otherwise we need
644        // to join the thread before replacing them.
645        for (std::thread& thread : pool) {
646          if (thread.joinable())
647            thread.join();
648        }
649        for (std::size_t ti = 0; ti < pool.size(); ++ti) {
650            pool[ti] = std::thread(&RunInThread, &b, iters, ti, &total);
651        }
652      } else {
653        // Run directly in this thread
654        RunInThread(&b, iters, 0, &total);
655      }
656      done.WaitForNotification();
657      running_benchmark = false;
658
659      const double cpu_accumulated_time = timer_manager->cpu_time_used();
660      const double real_accumulated_time = timer_manager->real_time_used();
661      timer_manager.reset();
662
663      VLOG(2) << "Ran in " << cpu_accumulated_time << "/"
664              << real_accumulated_time << "\n";
665
666      // Base decisions off of real time if requested by this benchmark.
667      double seconds = cpu_accumulated_time;
668      if (b.use_real_time) {
669          seconds = real_accumulated_time;
670      }
671
672      std::string label;
673      {
674        MutexLock l(GetBenchmarkLock());
675        label = *GetReportLabel();
676      }
677
678      const double min_time = !IsZero(b.min_time) ? b.min_time
679                                                  : FLAGS_benchmark_min_time;
680
681      // If this was the first run, was elapsed time or cpu time large enough?
682      // If this is not the first run, go with the current value of iter.
683      if ((i > 0) ||
684          (iters >= kMaxIterations) ||
685          (seconds >= min_time) ||
686          (real_accumulated_time >= 5*min_time)) {
687        double bytes_per_second = 0;
688        if (total.bytes_processed > 0 && seconds > 0.0) {
689          bytes_per_second = (total.bytes_processed / seconds);
690        }
691        double items_per_second = 0;
692        if (total.items_processed > 0 && seconds > 0.0) {
693          items_per_second = (total.items_processed / seconds);
694        }
695
696        // Create report about this benchmark run.
697        BenchmarkReporter::Run report;
698        report.benchmark_name = b.name;
699        report.report_label = label;
700        // Report the total iterations across all threads.
701        report.iterations = static_cast<int64_t>(iters) * b.threads;
702        report.real_accumulated_time = real_accumulated_time;
703        report.cpu_accumulated_time = cpu_accumulated_time;
704        report.bytes_per_second = bytes_per_second;
705        report.items_per_second = items_per_second;
706        reports.push_back(report);
707        break;
708      }
709
710      // See how much iterations should be increased by
711      // Note: Avoid division by zero with max(seconds, 1ns).
712      double multiplier = min_time * 1.4 / std::max(seconds, 1e-9);
713      // If our last run was at least 10% of FLAGS_benchmark_min_time then we
714      // use the multiplier directly. Otherwise we use at most 10 times
715      // expansion.
716      // NOTE: When the last run was at least 10% of the min time the max
717      // expansion should be 14x.
718      bool is_significant = (seconds / min_time) > 0.1;
719      multiplier = is_significant ? multiplier : std::min(10.0, multiplier);
720      if (multiplier <= 1.0) multiplier = 2.0;
721      double next_iters = std::max(multiplier * iters, iters + 1.0);
722      if (next_iters > kMaxIterations) {
723        next_iters = kMaxIterations;
724      }
725      VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n";
726      iters = static_cast<int>(next_iters + 0.5);
727    }
728  }
729  br->ReportRuns(reports);
730  if (b.multithreaded) {
731    for (std::thread& thread : pool)
732      thread.join();
733  }
734}
735
736}  // namespace
737
738State::State(size_t max_iters, bool has_x, int x, bool has_y, int y,
739             int thread_i)
740    : started_(false), total_iterations_(0),
741      has_range_x_(has_x), range_x_(x),
742      has_range_y_(has_y), range_y_(y),
743      bytes_processed_(0), items_processed_(0),
744      thread_index(thread_i),
745      max_iterations(max_iters)
746{
747    CHECK(max_iterations != 0) << "At least one iteration must be run";
748}
749
750void State::PauseTiming() {
751  // Add in time accumulated so far
752  CHECK(running_benchmark);
753  timer_manager->StopTimer();
754}
755
756void State::ResumeTiming() {
757  CHECK(running_benchmark);
758  timer_manager->StartTimer();
759}
760
761void State::SetLabel(const char* label) {
762  CHECK(running_benchmark);
763  MutexLock l(GetBenchmarkLock());
764  *GetReportLabel() = label;
765}
766
767namespace internal {
768namespace {
769
770void PrintBenchmarkList() {
771  std::vector<Benchmark::Instance> benchmarks;
772  auto families = BenchmarkFamilies::GetInstance();
773  if (!families->FindBenchmarks(".", &benchmarks)) return;
774
775  for (const internal::Benchmark::Instance& benchmark : benchmarks) {
776    std::cout <<  benchmark.name << "\n";
777  }
778}
779
780void RunMatchingBenchmarks(const std::string& spec,
781                           BenchmarkReporter* reporter) {
782  CHECK(reporter != nullptr);
783  if (spec.empty()) return;
784
785  std::vector<Benchmark::Instance> benchmarks;
786  auto families = BenchmarkFamilies::GetInstance();
787  if (!families->FindBenchmarks(spec, &benchmarks)) return;
788
789  // Determine the width of the name field using a minimum width of 10.
790  size_t name_field_width = 10;
791  for (const Benchmark::Instance& benchmark : benchmarks) {
792    name_field_width =
793        std::max<size_t>(name_field_width, benchmark.name.size());
794  }
795  if (FLAGS_benchmark_repetitions > 1)
796    name_field_width += std::strlen("_stddev");
797
798  // Print header here
799  BenchmarkReporter::Context context;
800  context.num_cpus = NumCPUs();
801  context.mhz_per_cpu = CyclesPerSecond() / 1000000.0f;
802
803  context.cpu_scaling_enabled = CpuScalingEnabled();
804  context.name_field_width = name_field_width;
805
806  if (reporter->ReportContext(context)) {
807    for (const auto& benchmark : benchmarks) {
808      RunBenchmark(benchmark, reporter);
809    }
810  }
811}
812
813std::unique_ptr<BenchmarkReporter> GetDefaultReporter() {
814  typedef std::unique_ptr<BenchmarkReporter> PtrType;
815  if (FLAGS_benchmark_format == "tabular") {
816    return PtrType(new ConsoleReporter);
817  } else if (FLAGS_benchmark_format == "json") {
818    return PtrType(new JSONReporter);
819  } else if (FLAGS_benchmark_format == "csv") {
820    return PtrType(new CSVReporter);
821  } else {
822    std::cerr << "Unexpected format: '" << FLAGS_benchmark_format << "'\n";
823    std::exit(1);
824  }
825}
826
827} // end namespace
828} // end namespace internal
829
830void RunSpecifiedBenchmarks() {
831  RunSpecifiedBenchmarks(nullptr);
832}
833
834void RunSpecifiedBenchmarks(BenchmarkReporter* reporter) {
835  if (FLAGS_benchmark_list_tests) {
836    internal::PrintBenchmarkList();
837    return;
838  }
839  std::string spec = FLAGS_benchmark_filter;
840  if (spec.empty() || spec == "all")
841    spec = ".";  // Regexp that matches all benchmarks
842
843  std::unique_ptr<BenchmarkReporter> default_reporter;
844  if (!reporter) {
845    default_reporter = internal::GetDefaultReporter();
846    reporter = default_reporter.get();
847  }
848  internal::RunMatchingBenchmarks(spec, reporter);
849  reporter->Finalize();
850}
851
852namespace internal {
853
854void PrintUsageAndExit() {
855  fprintf(stdout,
856          "benchmark"
857          " [--benchmark_list_tests={true|false}]\n"
858          "          [--benchmark_filter=<regex>]\n"
859          "          [--benchmark_min_time=<min_time>]\n"
860          "          [--benchmark_repetitions=<num_repetitions>]\n"
861          "          [--benchmark_format=<tabular|json|csv>]\n"
862          "          [--color_print={true|false}]\n"
863          "          [--v=<verbosity>]\n");
864  exit(0);
865}
866
867void ParseCommandLineFlags(int* argc, char** argv) {
868  using namespace benchmark;
869  for (int i = 1; i < *argc; ++i) {
870    if (
871        ParseBoolFlag(argv[i], "benchmark_list_tests",
872                      &FLAGS_benchmark_list_tests) ||
873        ParseStringFlag(argv[i], "benchmark_filter",
874                        &FLAGS_benchmark_filter) ||
875        ParseDoubleFlag(argv[i], "benchmark_min_time",
876                        &FLAGS_benchmark_min_time) ||
877        ParseInt32Flag(argv[i], "benchmark_repetitions",
878                       &FLAGS_benchmark_repetitions) ||
879        ParseStringFlag(argv[i], "benchmark_format",
880                        &FLAGS_benchmark_format) ||
881        ParseBoolFlag(argv[i], "color_print",
882                       &FLAGS_color_print) ||
883        ParseInt32Flag(argv[i], "v", &FLAGS_v)) {
884      for (int j = i; j != *argc; ++j) argv[j] = argv[j + 1];
885
886      --(*argc);
887      --i;
888    } else if (IsFlag(argv[i], "help")) {
889      PrintUsageAndExit();
890    }
891  }
892  if (FLAGS_benchmark_format != "tabular" &&
893      FLAGS_benchmark_format != "json" &&
894      FLAGS_benchmark_format != "csv") {
895    PrintUsageAndExit();
896  }
897}
898
899Benchmark* RegisterBenchmarkInternal(Benchmark* bench) {
900    std::unique_ptr<Benchmark> bench_ptr(bench);
901    BenchmarkFamilies* families = BenchmarkFamilies::GetInstance();
902    families->AddBenchmark(std::move(bench_ptr));
903    return bench;
904}
905
906} // end namespace internal
907
908void Initialize(int* argc, char** argv) {
909  internal::ParseCommandLineFlags(argc, argv);
910  internal::SetLogLevel(FLAGS_v);
911  // TODO remove this. It prints some output the first time it is called.
912  // We don't want to have this ouput printed during benchmarking.
913  MyCPUUsage();
914  // The first call to walltime::Now initialized it. Call it once to
915  // prevent the initialization from happening in a benchmark.
916  walltime::Now();
917}
918
919} // end namespace benchmark
trunk/3rdparty/benchmark/src/check.h
r0r253077
1#ifndef CHECK_H_
2#define CHECK_H_
3
4#include <cstdlib>
5#include <ostream>
6
7#include "internal_macros.h"
8#include "log.h"
9
10namespace benchmark {
11namespace internal {
12
13// CheckHandler is the class constructed by failing CHECK macros. CheckHandler
14// will log information about the failures and abort when it is destructed.
15class CheckHandler {
16public:
17  CheckHandler(const char* check, const char* file, const char* func, int line)
18    : log_(GetErrorLogInstance())
19  {
20    log_ << file << ":" << line << ": " << func << ": Check `"
21          << check << "' failed. ";
22  }
23
24  std::ostream& GetLog() {
25    return log_;
26  }
27
28  BENCHMARK_NORETURN ~CheckHandler() {
29      log_ << std::endl;
30      std::abort();
31  }
32
33  CheckHandler & operator=(const CheckHandler&) = delete;
34  CheckHandler(const CheckHandler&) = delete;
35  CheckHandler() = delete;
36private:
37  std::ostream& log_;
38};
39
40} // end namespace internal
41} // end namespace benchmark
42
43// The CHECK macro returns a std::ostream object that can have extra information
44// written to it.
45#ifndef NDEBUG
46# define CHECK(b)  (b ? ::benchmark::internal::GetNullLogInstance()        \
47                      : ::benchmark::internal::CheckHandler(               \
48                          #b, __FILE__, __func__, __LINE__).GetLog())
49#else
50# define CHECK(b) ::benchmark::internal::GetNullLogInstance()
51#endif
52
53#define CHECK_EQ(a, b) CHECK((a) == (b))
54#define CHECK_NE(a, b) CHECK((a) != (b))
55#define CHECK_GE(a, b) CHECK((a) >= (b))
56#define CHECK_LE(a, b) CHECK((a) <= (b))
57#define CHECK_GT(a, b) CHECK((a) > (b))
58#define CHECK_LT(a, b) CHECK((a) < (b))
59
60#endif  // CHECK_H_
trunk/3rdparty/benchmark/src/colorprint.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "colorprint.h"
16
17#include <cstdarg>
18#include <cstdio>
19
20#include "commandlineflags.h"
21#include "internal_macros.h"
22
23#ifdef BENCHMARK_OS_WINDOWS
24#include <Windows.h>
25#endif
26
27DECLARE_bool(color_print);
28
29namespace benchmark {
30namespace {
31#ifdef BENCHMARK_OS_WINDOWS
32typedef WORD PlatformColorCode;
33#else
34typedef const char* PlatformColorCode;
35#endif
36
37PlatformColorCode GetPlatformColorCode(LogColor color) {
38#ifdef BENCHMARK_OS_WINDOWS
39  switch (color) {
40    case COLOR_RED:
41      return FOREGROUND_RED;
42    case COLOR_GREEN:
43      return FOREGROUND_GREEN;
44    case COLOR_YELLOW:
45      return FOREGROUND_RED | FOREGROUND_GREEN;
46    case COLOR_BLUE:
47      return FOREGROUND_BLUE;
48    case COLOR_MAGENTA:
49      return FOREGROUND_BLUE | FOREGROUND_RED;
50    case COLOR_CYAN:
51      return FOREGROUND_BLUE | FOREGROUND_GREEN;
52    case COLOR_WHITE:  // fall through to default
53    default:
54      return 0;
55  }
56#else
57  switch (color) {
58    case COLOR_RED:
59      return "1";
60    case COLOR_GREEN:
61      return "2";
62    case COLOR_YELLOW:
63      return "3";
64    case COLOR_BLUE:
65      return "4";
66    case COLOR_MAGENTA:
67      return "5";
68    case COLOR_CYAN:
69      return "6";
70    case COLOR_WHITE:
71      return "7";
72    default:
73      return nullptr;
74  };
75#endif
76}
77}  // end namespace
78
79void ColorPrintf(LogColor color, const char* fmt, ...) {
80  va_list args;
81  va_start(args, fmt);
82
83  if (!FLAGS_color_print) {
84    vprintf(fmt, args);
85    va_end(args);
86    return;
87  }
88
89#ifdef BENCHMARK_OS_WINDOWS
90  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
91
92  // Gets the current text color.
93  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
94  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
95  const WORD old_color_attrs = buffer_info.wAttributes;
96
97  // We need to flush the stream buffers into the console before each
98  // SetConsoleTextAttribute call lest it affect the text that is already
99  // printed but has not yet reached the console.
100  fflush(stdout);
101  SetConsoleTextAttribute(stdout_handle,
102                          GetPlatformColorCode(color) | FOREGROUND_INTENSITY);
103  vprintf(fmt, args);
104
105  fflush(stdout);
106  // Restores the text color.
107  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
108#else
109  const char* color_code = GetPlatformColorCode(color);
110  if (color_code) fprintf(stdout, "\033[0;3%sm", color_code);
111  vprintf(fmt, args);
112  printf("\033[m");  // Resets the terminal to default.
113#endif
114  va_end(args);
115}
116}  // end namespace benchmark
trunk/3rdparty/benchmark/src/colorprint.h
r0r253077
1#ifndef BENCHMARK_COLORPRINT_H_
2#define BENCHMARK_COLORPRINT_H_
3
4namespace benchmark {
5enum LogColor {
6  COLOR_DEFAULT,
7  COLOR_RED,
8  COLOR_GREEN,
9  COLOR_YELLOW,
10  COLOR_BLUE,
11  COLOR_MAGENTA,
12  COLOR_CYAN,
13  COLOR_WHITE
14};
15
16void ColorPrintf(LogColor color, const char* fmt, ...);
17}  // end namespace benchmark
18
19#endif  // BENCHMARK_COLORPRINT_H_
trunk/3rdparty/benchmark/src/commandlineflags.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "commandlineflags.h"
16
17#include <cstdlib>
18#include <cstring>
19#include <iostream>
20#include <limits>
21
22namespace benchmark {
23// Parses 'str' for a 32-bit signed integer.  If successful, writes
24// the result to *value and returns true; otherwise leaves *value
25// unchanged and returns false.
26bool ParseInt32(const std::string& src_text, const char* str, int32_t* value) {
27  // Parses the environment variable as a decimal integer.
28  char* end = nullptr;
29  const long long_value = strtol(str, &end, 10);  // NOLINT
30
31  // Has strtol() consumed all characters in the string?
32  if (*end != '\0') {
33    // No - an invalid character was encountered.
34    std::cerr << src_text << " is expected to be a 32-bit integer, "
35              << "but actually has value \"" << str << "\".\n";
36    return false;
37  }
38
39  // Is the parsed value in the range of an Int32?
40  const int32_t result = static_cast<int32_t>(long_value);
41  if (long_value == std::numeric_limits<long>::max() ||
42      long_value == std::numeric_limits<long>::min() ||
43      // The parsed value overflows as a long.  (strtol() returns
44      // LONG_MAX or LONG_MIN when the input overflows.)
45      result != long_value
46          // The parsed value overflows as an Int32.
47      ) {
48    std::cerr << src_text << " is expected to be a 32-bit integer, "
49              << "but actually has value \"" << str << "\", "
50              << "which overflows.\n";
51    return false;
52  }
53
54  *value = result;
55  return true;
56}
57
58// Parses 'str' for a double.  If successful, writes the result to *value and
59// returns true; otherwise leaves *value unchanged and returns false.
60bool ParseDouble(const std::string& src_text, const char* str, double* value) {
61  // Parses the environment variable as a decimal integer.
62  char* end = nullptr;
63  const double double_value = strtod(str, &end);  // NOLINT
64
65  // Has strtol() consumed all characters in the string?
66  if (*end != '\0') {
67    // No - an invalid character was encountered.
68    std::cerr << src_text << " is expected to be a double, "
69              << "but actually has value \"" << str << "\".\n";
70    return false;
71  }
72
73  *value = double_value;
74  return true;
75}
76
77inline const char* GetEnv(const char* name) {
78#if defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
79  // Environment variables which we programmatically clear will be set to the
80  // empty string rather than unset (nullptr).  Handle that case.
81  const char* const env = getenv(name);
82  return (env != nullptr && env[0] != '\0') ? env : nullptr;
83#else
84  return getenv(name);
85#endif
86}
87
88// Returns the name of the environment variable corresponding to the
89// given flag.  For example, FlagToEnvVar("foo") will return
90// "BENCHMARK_FOO" in the open-source version.
91static std::string FlagToEnvVar(const char* flag) {
92  const std::string flag_str(flag);
93
94  std::string env_var;
95  for (size_t i = 0; i != flag_str.length(); ++i)
96    env_var += static_cast<char>(::toupper(flag_str.c_str()[i]));
97
98  return "BENCHMARK_" + env_var;
99}
100
101// Reads and returns the Boolean environment variable corresponding to
102// the given flag; if it's not set, returns default_value.
103//
104// The value is considered true iff it's not "0".
105bool BoolFromEnv(const char* flag, bool default_value) {
106  const std::string env_var = FlagToEnvVar(flag);
107  const char* const string_value = GetEnv(env_var.c_str());
108  return string_value == nullptr ? default_value : strcmp(string_value, "0") != 0;
109}
110
111// Reads and returns a 32-bit integer stored in the environment
112// variable corresponding to the given flag; if it isn't set or
113// doesn't represent a valid 32-bit integer, returns default_value.
114int32_t Int32FromEnv(const char* flag, int32_t default_value) {
115  const std::string env_var = FlagToEnvVar(flag);
116  const char* const string_value = GetEnv(env_var.c_str());
117  if (string_value == nullptr) {
118    // The environment variable is not set.
119    return default_value;
120  }
121
122  int32_t result = default_value;
123  if (!ParseInt32(std::string("Environment variable ") + env_var, string_value,
124                  &result)) {
125    std::cout << "The default value " << default_value << " is used.\n";
126    return default_value;
127  }
128
129  return result;
130}
131
132// Reads and returns the string environment variable corresponding to
133// the given flag; if it's not set, returns default_value.
134const char* StringFromEnv(const char* flag, const char* default_value) {
135  const std::string env_var = FlagToEnvVar(flag);
136  const char* const value = GetEnv(env_var.c_str());
137  return value == nullptr ? default_value : value;
138}
139
140// Parses a string as a command line flag.  The string should have
141// the format "--flag=value".  When def_optional is true, the "=value"
142// part can be omitted.
143//
144// Returns the value of the flag, or nullptr if the parsing failed.
145const char* ParseFlagValue(const char* str, const char* flag,
146                           bool def_optional) {
147  // str and flag must not be nullptr.
148  if (str == nullptr || flag == nullptr) return nullptr;
149
150  // The flag must start with "--".
151  const std::string flag_str = std::string("--") + std::string(flag);
152  const size_t flag_len = flag_str.length();
153  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
154
155  // Skips the flag name.
156  const char* flag_end = str + flag_len;
157
158  // When def_optional is true, it's OK to not have a "=value" part.
159  if (def_optional && (flag_end[0] == '\0')) return flag_end;
160
161  // If def_optional is true and there are more characters after the
162  // flag name, or if def_optional is false, there must be a '=' after
163  // the flag name.
164  if (flag_end[0] != '=') return nullptr;
165
166  // Returns the string after "=".
167  return flag_end + 1;
168}
169
170bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
171  // Gets the value of the flag as a string.
172  const char* const value_str = ParseFlagValue(str, flag, true);
173
174  // Aborts if the parsing failed.
175  if (value_str == nullptr) return false;
176
177  // Converts the string value to a bool.
178  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
179  return true;
180}
181
182bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {
183  // Gets the value of the flag as a string.
184  const char* const value_str = ParseFlagValue(str, flag, false);
185
186  // Aborts if the parsing failed.
187  if (value_str == nullptr) return false;
188
189  // Sets *value to the value of the flag.
190  return ParseInt32(std::string("The value of flag --") + flag, value_str,
191                    value);
192}
193
194bool ParseDoubleFlag(const char* str, const char* flag, double* value) {
195  // Gets the value of the flag as a string.
196  const char* const value_str = ParseFlagValue(str, flag, false);
197
198  // Aborts if the parsing failed.
199  if (value_str == nullptr) return false;
200
201  // Sets *value to the value of the flag.
202  return ParseDouble(std::string("The value of flag --") + flag, value_str,
203                     value);
204}
205
206bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
207  // Gets the value of the flag as a string.
208  const char* const value_str = ParseFlagValue(str, flag, false);
209
210  // Aborts if the parsing failed.
211  if (value_str == nullptr) return false;
212
213  *value = value_str;
214  return true;
215}
216
217bool IsFlag(const char* str, const char* flag) {
218  return (ParseFlagValue(str, flag, true) != nullptr);
219}
220}  // end namespace benchmark
trunk/3rdparty/benchmark/src/commandlineflags.h
r0r253077
1#ifndef BENCHMARK_COMMANDLINEFLAGS_H_
2#define BENCHMARK_COMMANDLINEFLAGS_H_
3
4#include <cstdint>
5#include <string>
6
7// Macro for referencing flags.
8#define FLAG(name) FLAGS_##name
9
10// Macros for declaring flags.
11#define DECLARE_bool(name) extern bool FLAG(name)
12#define DECLARE_int32(name) extern int32_t FLAG(name)
13#define DECLARE_int64(name) extern int64_t FLAG(name)
14#define DECLARE_double(name) extern double FLAG(name)
15#define DECLARE_string(name) extern std::string FLAG(name)
16
17// Macros for defining flags.
18#define DEFINE_bool(name, default_val, doc) bool FLAG(name) = (default_val)
19#define DEFINE_int32(name, default_val, doc) int32_t FLAG(name) = (default_val)
20#define DEFINE_int64(name, default_val, doc) int64_t FLAG(name) = (default_val)
21#define DEFINE_double(name, default_val, doc) double FLAG(name) = (default_val)
22#define DEFINE_string(name, default_val, doc) \
23  std::string FLAG(name) = (default_val)
24
25namespace benchmark {
26// Parses 'str' for a 32-bit signed integer.  If successful, writes the result
27// to *value and returns true; otherwise leaves *value unchanged and returns
28// false.
29bool ParseInt32(const std::string& src_text, const char* str, int32_t* value);
30
31// Parses a bool/Int32/string from the environment variable
32// corresponding to the given Google Test flag.
33bool BoolFromEnv(const char* flag, bool default_val);
34int32_t Int32FromEnv(const char* flag, int32_t default_val);
35double DoubleFromEnv(const char* flag, double default_val);
36const char* StringFromEnv(const char* flag, const char* default_val);
37
38// Parses a string for a bool flag, in the form of either
39// "--flag=value" or "--flag".
40//
41// In the former case, the value is taken as true as long as it does
42// not start with '0', 'f', or 'F'.
43//
44// In the latter case, the value is taken as true.
45//
46// On success, stores the value of the flag in *value, and returns
47// true.  On failure, returns false without changing *value.
48bool ParseBoolFlag(const char* str, const char* flag, bool* value);
49
50// Parses a string for an Int32 flag, in the form of
51// "--flag=value".
52//
53// On success, stores the value of the flag in *value, and returns
54// true.  On failure, returns false without changing *value.
55bool ParseInt32Flag(const char* str, const char* flag, int32_t* value);
56
57// Parses a string for a Double flag, in the form of
58// "--flag=value".
59//
60// On success, stores the value of the flag in *value, and returns
61// true.  On failure, returns false without changing *value.
62bool ParseDoubleFlag(const char* str, const char* flag, double* value);
63
64// Parses a string for a string flag, in the form of
65// "--flag=value".
66//
67// On success, stores the value of the flag in *value, and returns
68// true.  On failure, returns false without changing *value.
69bool ParseStringFlag(const char* str, const char* flag, std::string* value);
70
71// Returns true if the string matches the flag.
72bool IsFlag(const char* str, const char* flag);
73
74}  // end namespace benchmark
75
76#endif  // BENCHMARK_COMMANDLINEFLAGS_H_
trunk/3rdparty/benchmark/src/console_reporter.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "benchmark/reporter.h"
16
17#include <cstdint>
18#include <cstdio>
19#include <iostream>
20#include <string>
21#include <vector>
22
23#include "check.h"
24#include "colorprint.h"
25#include "string_util.h"
26#include "walltime.h"
27
28namespace benchmark {
29
30bool ConsoleReporter::ReportContext(const Context& context) {
31  name_field_width_ = context.name_field_width;
32
33  std::cerr << "Run on (" << context.num_cpus << " X " << context.mhz_per_cpu
34            << " MHz CPU " << ((context.num_cpus > 1) ? "s" : "") << ")\n";
35
36  std::cerr << LocalDateTimeString() << "\n";
37
38  if (context.cpu_scaling_enabled) {
39    std::cerr << "***WARNING*** CPU scaling is enabled, the benchmark "
40                 "real time measurements may be noisy and will incure extra "
41                 "overhead.\n";
42  }
43
44#ifndef NDEBUG
45  std::cerr << "***WARNING*** Library was built as DEBUG. Timings may be "
46               "affected.\n";
47#endif
48
49  int output_width = fprintf(stdout, "%-*s %10s %10s %10s\n",
50                             static_cast<int>(name_field_width_), "Benchmark",
51                             "Time(ns)", "CPU(ns)", "Iterations");
52  std::cout << std::string(output_width - 1, '-') << "\n";
53
54  return true;
55}
56
57void ConsoleReporter::ReportRuns(const std::vector<Run>& reports) {
58  if (reports.empty()) {
59    return;
60  }
61
62  for (Run const& run : reports) {
63    CHECK_EQ(reports[0].benchmark_name, run.benchmark_name);
64    PrintRunData(run);
65  }
66
67  if (reports.size() < 2) {
68    // We don't report aggregated data if there was a single run.
69    return;
70  }
71
72  Run mean_data;
73  Run stddev_data;
74  BenchmarkReporter::ComputeStats(reports, &mean_data, &stddev_data);
75
76  // Output using PrintRun.
77  PrintRunData(mean_data);
78  PrintRunData(stddev_data);
79}
80
81void ConsoleReporter::PrintRunData(const Run& result) {
82  // Format bytes per second
83  std::string rate;
84  if (result.bytes_per_second > 0) {
85    rate = StrCat(" ", HumanReadableNumber(result.bytes_per_second), "B/s");
86  }
87
88  // Format items per second
89  std::string items;
90  if (result.items_per_second > 0) {
91    items = StrCat(" ", HumanReadableNumber(result.items_per_second),
92                   " items/s");
93  }
94
95  double const multiplier = 1e9; // nano second multiplier
96  ColorPrintf(COLOR_GREEN, "%-*s ",
97              name_field_width_, result.benchmark_name.c_str());
98  if (result.iterations == 0) {
99    ColorPrintf(COLOR_YELLOW, "%10.0f %10.0f ",
100                result.real_accumulated_time * multiplier,
101                result.cpu_accumulated_time * multiplier);
102  } else {
103    ColorPrintf(COLOR_YELLOW, "%10.0f %10.0f ",
104                (result.real_accumulated_time * multiplier) /
105                    (static_cast<double>(result.iterations)),
106                (result.cpu_accumulated_time * multiplier) /
107                    (static_cast<double>(result.iterations)));
108  }
109  ColorPrintf(COLOR_CYAN, "%10lld", result.iterations);
110  ColorPrintf(COLOR_DEFAULT, "%*s %*s %s\n",
111              13, rate.c_str(),
112              18, items.c_str(),
113              result.report_label.c_str());
114}
115
116}  // end namespace benchmark
trunk/3rdparty/benchmark/src/csv_reporter.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "benchmark/reporter.h"
16
17#include <cstdint>
18#include <iostream>
19#include <string>
20#include <vector>
21
22#include "string_util.h"
23#include "walltime.h"
24
25// File format reference: http://edoceo.com/utilitas/csv-file-format.
26
27namespace benchmark {
28
29bool CSVReporter::ReportContext(const Context& context) {
30  std::cerr << "Run on (" << context.num_cpus << " X " << context.mhz_per_cpu
31            << " MHz CPU " << ((context.num_cpus > 1) ? "s" : "") << ")\n";
32
33  std::cerr << LocalDateTimeString() << "\n";
34
35  if (context.cpu_scaling_enabled) {
36    std::cerr << "***WARNING*** CPU scaling is enabled, the benchmark "
37                 "real time measurements may be noisy and will incure extra "
38                 "overhead.\n";
39  }
40
41#ifndef NDEBUG
42  std::cerr << "***WARNING*** Library was built as DEBUG. Timings may be "
43               "affected.\n";
44#endif
45  std::cout << "name,iterations,real_time,cpu_time,bytes_per_second,"
46               "items_per_second,label\n";
47  return true;
48}
49
50void CSVReporter::ReportRuns(std::vector<Run> const& reports) {
51  if (reports.empty()) {
52    return;
53  }
54
55  std::vector<Run> reports_cp = reports;
56  if (reports.size() >= 2) {
57    Run mean_data;
58    Run stddev_data;
59    BenchmarkReporter::ComputeStats(reports, &mean_data, &stddev_data);
60    reports_cp.push_back(mean_data);
61    reports_cp.push_back(stddev_data);
62  }
63  for (auto it = reports_cp.begin(); it != reports_cp.end(); ++it) {
64    PrintRunData(*it);
65  }
66}
67
68void CSVReporter::PrintRunData(Run const& run) {
69  double const multiplier = 1e9;  // nano second multiplier
70  double cpu_time = run.cpu_accumulated_time * multiplier;
71  double real_time = run.real_accumulated_time * multiplier;
72  if (run.iterations != 0) {
73    real_time = real_time / static_cast<double>(run.iterations);
74    cpu_time = cpu_time / static_cast<double>(run.iterations);
75  }
76
77  // Field with embedded double-quote characters must be doubled and the field
78  // delimited with double-quotes.
79  std::string name = run.benchmark_name;
80  ReplaceAll(&name, "\"", "\"\"");
81  std::cout << "\"" << name << "\",";
82
83  std::cout << run.iterations << ",";
84  std::cout << real_time << ",";
85  std::cout << cpu_time << ",";
86
87  if (run.bytes_per_second > 0.0) {
88    std::cout << run.bytes_per_second;
89  }
90  std::cout << ",";
91  if (run.items_per_second > 0.0) {
92    std::cout << run.items_per_second;
93  }
94  std::cout << ",";
95  if (!run.report_label.empty()) {
96    // Field with embedded double-quote characters must be doubled and the field
97    // delimited with double-quotes.
98    std::string label = run.report_label;
99    ReplaceAll(&label, "\"", "\"\"");
100    std::cout << "\"" << label << "\"";
101  }
102  std::cout << '\n';
103}
104
105}  // end namespace benchmark
trunk/3rdparty/benchmark/src/cycleclock.h
r0r253077
1// ----------------------------------------------------------------------
2// CycleClock
3//    A CycleClock tells you the current time in Cycles.  The "time"
4//    is actually time since power-on.  This is like time() but doesn't
5//    involve a system call and is much more precise.
6//
7// NOTE: Not all cpu/platform/kernel combinations guarantee that this
8// clock increments at a constant rate or is synchronized across all logical
9// cpus in a system.
10//
11// If you need the above guarantees, please consider using a different
12// API. There are efforts to provide an interface which provides a millisecond
13// granularity and implemented as a memory read. A memory read is generally
14// cheaper than the CycleClock for many architectures.
15//
16// Also, in some out of order CPU implementations, the CycleClock is not
17// serializing. So if you're trying to count at cycles granularity, your
18// data might be inaccurate due to out of order instruction execution.
19// ----------------------------------------------------------------------
20
21#ifndef BENCHMARK_CYCLECLOCK_H_
22#define BENCHMARK_CYCLECLOCK_H_
23
24#include <cstdint>
25
26#include "benchmark/macros.h"
27#include "internal_macros.h"
28
29#if defined(BENCHMARK_OS_MACOSX)
30#include <mach/mach_time.h>
31#endif
32// For MSVC, we want to use '_asm rdtsc' when possible (since it works
33// with even ancient MSVC compilers), and when not possible the
34// __rdtsc intrinsic, declared in <intrin.h>.  Unfortunately, in some
35// environments, <windows.h> and <intrin.h> have conflicting
36// declarations of some other intrinsics, breaking compilation.
37// Therefore, we simply declare __rdtsc ourselves. See also
38// http://connect.microsoft.com/VisualStudio/feedback/details/262047
39#if defined(COMPILER_MSVC) && !defined(_M_IX86)
40extern "C" uint64_t __rdtsc();
41#pragma intrinsic(__rdtsc)
42#endif
43
44#ifndef BENCHMARK_OS_WINDOWS
45#include <sys/time.h>
46#endif
47
48namespace benchmark {
49// NOTE: only i386 and x86_64 have been well tested.
50// PPC, sparc, alpha, and ia64 are based on
51//    http://peter.kuscsik.com/wordpress/?p=14
52// with modifications by m3b.  See also
53//    https://setisvn.ssl.berkeley.edu/svn/lib/fftw-3.0.1/kernel/cycle.h
54namespace cycleclock {
55// This should return the number of cycles since power-on.  Thread-safe.
56inline BENCHMARK_ALWAYS_INLINE int64_t Now() {
57#if defined(BENCHMARK_OS_MACOSX)
58  // this goes at the top because we need ALL Macs, regardless of
59  // architecture, to return the number of "mach time units" that
60  // have passed since startup.  See sysinfo.cc where
61  // InitializeSystemInfo() sets the supposed cpu clock frequency of
62  // macs to the number of mach time units per second, not actual
63  // CPU clock frequency (which can change in the face of CPU
64  // frequency scaling).  Also note that when the Mac sleeps, this
65  // counter pauses; it does not continue counting, nor does it
66  // reset to zero.
67  return mach_absolute_time();
68#elif defined(__i386__)
69  int64_t ret;
70  __asm__ volatile("rdtsc" : "=A"(ret));
71  return ret;
72#elif defined(__x86_64__) || defined(__amd64__)
73  uint64_t low, high;
74  __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
75  return (high << 32) | low;
76#elif defined(__powerpc__) || defined(__ppc__)
77  // This returns a time-base, which is not always precisely a cycle-count.
78  int64_t tbl, tbu0, tbu1;
79  asm("mftbu %0" : "=r"(tbu0));
80  asm("mftb  %0" : "=r"(tbl));
81  asm("mftbu %0" : "=r"(tbu1));
82  tbl &= -static_cast<int64>(tbu0 == tbu1);
83  // high 32 bits in tbu1; low 32 bits in tbl  (tbu0 is garbage)
84  return (tbu1 << 32) | tbl;
85#elif defined(__sparc__)
86  int64_t tick;
87  asm(".byte 0x83, 0x41, 0x00, 0x00");
88  asm("mov   %%g1, %0" : "=r"(tick));
89  return tick;
90#elif defined(__ia64__)
91  int64_t itc;
92  asm("mov %0 = ar.itc" : "=r"(itc));
93  return itc;
94#elif defined(COMPILER_MSVC) && defined(_M_IX86)
95  // Older MSVC compilers (like 7.x) don't seem to support the
96  // __rdtsc intrinsic properly, so I prefer to use _asm instead
97  // when I know it will work.  Otherwise, I'll use __rdtsc and hope
98  // the code is being compiled with a non-ancient compiler.
99  _asm rdtsc
100#elif defined(COMPILER_MSVC)
101  return __rdtsc();
102#elif defined(__ARM_ARCH)
103#if (__ARM_ARCH >= 6)  // V6 is the earliest arch that has a standard cyclecount
104  uint32_t pmccntr;
105  uint32_t pmuseren;
106  uint32_t pmcntenset;
107  // Read the user mode perf monitor counter access permissions.
108  asm("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren));
109  if (pmuseren & 1) {  // Allows reading perfmon counters for user mode code.
110    asm("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset));
111    if (pmcntenset & 0x80000000ul) {  // Is it counting?
112      asm("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr));
113      // The counter is set up to count every 64th cycle
114      return static_cast<int64_t>(pmccntr) * 64;  // Should optimize to << 6
115    }
116  }
117#endif
118  struct timeval tv;
119  gettimeofday(&tv, nullptr);
120  return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
121#elif defined(__mips__)
122  // mips apparently only allows rdtsc for superusers, so we fall
123  // back to gettimeofday.  It's possible clock_gettime would be better.
124  struct timeval tv;
125  gettimeofday(&tv, nullptr);
126  return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
127#else
128// The soft failover to a generic implementation is automatic only for ARM.
129// For other platforms the developer is expected to make an attempt to create
130// a fast implementation and use generic version if nothing better is available.
131#error You need to define CycleTimer for your OS and CPU
132#endif
133}
134}  // end namespace cycleclock
135}  // end namespace benchmark
136
137#endif  // BENCHMARK_CYCLECLOCK_H_
trunk/3rdparty/benchmark/src/internal_macros.h
r0r253077
1#ifndef BENCHMARK_INTERNAL_MACROS_H_
2#define BENCHMARK_INTERNAL_MACROS_H_
3
4#include "benchmark/macros.h"
5
6#ifndef __has_feature
7# define __has_feature(x) 0
8#endif
9
10#if __has_feature(cxx_attributes)
11# define BENCHMARK_NORETURN [[noreturn]]
12#elif defined(__GNUC__)
13# define BENCHMARK_NORETURN __attribute__((noreturn))
14#else
15# define BENCHMARK_NORETURN
16#endif
17
18#if defined(__CYGWIN__)
19# define BENCHMARK_OS_CYGWIN 1
20#elif defined(_WIN32)
21# define BENCHMARK_OS_WINDOWS 1
22#elif defined(__APPLE__)
23// TODO(ericwf) This doesn't actually check that it is a Mac OSX system. Just
24// that it is an apple system.
25# define BENCHMARK_OS_MACOSX 1
26#elif defined(__FreeBSD__)
27# define BENCHMARK_OS_FREEBSD 1
28#elif defined(__linux__)
29# define BENCHMARK_OS_LINUX 1
30#endif
31
32#if defined(__clang__)
33# define COMPILER_CLANG
34#elif defined(_MSC_VER)
35# define COMPILER_MSVC
36#elif defined(__GNUC__)
37# define COMPILER_GCC
38#endif
39
40#endif // BENCHMARK_INTERNAL_MACROS_H_
trunk/3rdparty/benchmark/src/json_reporter.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "benchmark/reporter.h"
16
17#include <cstdint>
18#include <iostream>
19#include <string>
20#include <vector>
21
22#include "string_util.h"
23#include "walltime.h"
24
25namespace benchmark {
26
27namespace {
28
29std::string FormatKV(std::string const& key, std::string const& value) {
30  return StringPrintF("\"%s\": \"%s\"", key.c_str(), value.c_str());
31}
32
33std::string FormatKV(std::string const& key, const char* value) {
34  return StringPrintF("\"%s\": \"%s\"", key.c_str(), value);
35}
36
37std::string FormatKV(std::string const& key, bool value) {
38  return StringPrintF("\"%s\": %s", key.c_str(), value ? "true" : "false");
39}
40
41std::string FormatKV(std::string const& key, int64_t value) {
42  std::stringstream ss;
43  ss << '"' << key << "\": " << value;
44  return ss.str();
45}
46
47int64_t RoundDouble(double v) {
48    return static_cast<int64_t>(v + 0.5);
49}
50
51} // end namespace
52
53bool JSONReporter::ReportContext(const Context& context) {
54  std::ostream& out = std::cout;
55
56  out << "{\n";
57  std::string inner_indent(2, ' ');
58
59  // Open context block and print context information.
60  out << inner_indent << "\"context\": {\n";
61  std::string indent(4, ' ');
62
63  std::string walltime_value = LocalDateTimeString();
64  out << indent << FormatKV("date", walltime_value) << ",\n";
65
66  out << indent
67      << FormatKV("num_cpus", static_cast<int64_t>(context.num_cpus))
68      << ",\n";
69  out << indent
70      << FormatKV("mhz_per_cpu", RoundDouble(context.mhz_per_cpu))
71      << ",\n";
72  out << indent
73      << FormatKV("cpu_scaling_enabled", context.cpu_scaling_enabled)
74      << ",\n";
75
76#if defined(NDEBUG)
77  const char build_type[] = "release";
78#else
79  const char build_type[] = "debug";
80#endif
81  out << indent << FormatKV("library_build_type", build_type) << "\n";
82  // Close context block and open the list of benchmarks.
83  out << inner_indent << "},\n";
84  out << inner_indent << "\"benchmarks\": [\n";
85  return true;
86}
87
88void JSONReporter::ReportRuns(std::vector<Run> const& reports) {
89  if (reports.empty()) {
90    return;
91  }
92  std::string indent(4, ' ');
93  std::ostream& out = std::cout;
94  if (!first_report_) {
95    out << ",\n";
96  }
97  first_report_ = false;
98  std::vector<Run> reports_cp = reports;
99  if (reports.size() >= 2) {
100    Run mean_data;
101    Run stddev_data;
102    BenchmarkReporter::ComputeStats(reports, &mean_data, &stddev_data);
103    reports_cp.push_back(mean_data);
104    reports_cp.push_back(stddev_data);
105  }
106  for (auto it = reports_cp.begin(); it != reports_cp.end(); ++it) {
107     out << indent << "{\n";
108     PrintRunData(*it);
109     out << indent << '}';
110     auto it_cp = it;
111     if (++it_cp != reports_cp.end()) {
112         out << ",\n";
113     }
114  }
115}
116
117void JSONReporter::Finalize() {
118    // Close the list of benchmarks and the top level object.
119    std::cout << "\n  ]\n}\n";
120}
121
122void JSONReporter::PrintRunData(Run const& run) {
123    double const multiplier = 1e9; // nano second multiplier
124    double cpu_time = run.cpu_accumulated_time * multiplier;
125    double real_time = run.real_accumulated_time * multiplier;
126    if (run.iterations != 0) {
127        real_time = real_time / static_cast<double>(run.iterations);
128        cpu_time = cpu_time / static_cast<double>(run.iterations);
129    }
130
131    std::string indent(6, ' ');
132    std::ostream& out = std::cout;
133    out << indent
134        << FormatKV("name", run.benchmark_name)
135        << ",\n";
136    out << indent
137        << FormatKV("iterations", run.iterations)
138        << ",\n";
139    out << indent
140        << FormatKV("real_time", RoundDouble(real_time))
141        << ",\n";
142    out << indent
143        << FormatKV("cpu_time", RoundDouble(cpu_time));
144    if (run.bytes_per_second > 0.0) {
145        out << ",\n" << indent
146            << FormatKV("bytes_per_second", RoundDouble(run.bytes_per_second));
147    }
148    if (run.items_per_second > 0.0) {
149        out << ",\n" << indent
150            << FormatKV("items_per_second", RoundDouble(run.items_per_second));
151    }
152    if (!run.report_label.empty()) {
153        out << ",\n" << indent
154            << FormatKV("label", run.report_label);
155    }
156    out << '\n';
157}
158
159} // end namespace benchmark
trunk/3rdparty/benchmark/src/log.cc
r0r253077
1#include "log.h"
2
3#include <iostream>
4
5namespace benchmark {
6namespace internal {
7
8int& LoggingLevelImp() {
9    static int level = 0;
10    return level;
11}
12
13void SetLogLevel(int value) {
14    LoggingLevelImp() = value;
15}
16
17int GetLogLevel() {
18    return LoggingLevelImp();
19}
20
21class NullLogBuffer : public std::streambuf
22{
23public:
24  int overflow(int c) {
25    return c;
26  }
27};
28
29std::ostream& GetNullLogInstance() {
30  static NullLogBuffer log_buff;
31  static std::ostream null_log(&log_buff);
32  return null_log;
33}
34
35std::ostream& GetErrorLogInstance() {
36  return std::clog;
37}
38
39} // end namespace internal
40} // end namespace benchmark
No newline at end of file
trunk/3rdparty/benchmark/src/log.h
r0r253077
1#ifndef BENCHMARK_LOG_H_
2#define BENCHMARK_LOG_H_
3
4#include <ostream>
5
6namespace benchmark {
7namespace internal {
8
9int GetLogLevel();
10void SetLogLevel(int level);
11
12std::ostream& GetNullLogInstance();
13std::ostream& GetErrorLogInstance();
14
15inline std::ostream& GetLogInstanceForLevel(int level) {
16  if (level <= GetLogLevel()) {
17    return GetErrorLogInstance();
18  }
19  return GetNullLogInstance();
20}
21
22} // end namespace internal
23} // end namespace benchmark
24
25#define VLOG(x) (::benchmark::internal::GetLogInstanceForLevel(x) \
26                 << "-- LOG(" << x << "): ")
27
28#endif
No newline at end of file
trunk/3rdparty/benchmark/src/mutex.h
r0r253077
1#ifndef BENCHMARK_MUTEX_H_
2#define BENCHMARK_MUTEX_H_
3
4#include <mutex>
5#include <condition_variable>
6
7// Enable thread safety attributes only with clang.
8// The attributes can be safely erased when compiling with other compilers.
9#if defined(HAVE_THREAD_SAFETY_ATTRIBUTES)
10#define THREAD_ANNOTATION_ATTRIBUTE__(x)   __attribute__((x))
11#else
12#define THREAD_ANNOTATION_ATTRIBUTE__(x)   // no-op
13#endif
14
15#define CAPABILITY(x) \
16  THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
17
18#define SCOPED_CAPABILITY \
19  THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
20
21#define GUARDED_BY(x) \
22  THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
23
24#define PT_GUARDED_BY(x) \
25  THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
26
27#define ACQUIRED_BEFORE(...) \
28  THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
29
30#define ACQUIRED_AFTER(...) \
31  THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
32
33#define REQUIRES(...) \
34  THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
35
36#define REQUIRES_SHARED(...) \
37  THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
38
39#define ACQUIRE(...) \
40  THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
41
42#define ACQUIRE_SHARED(...) \
43  THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
44
45#define RELEASE(...) \
46  THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
47
48#define RELEASE_SHARED(...) \
49  THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
50
51#define TRY_ACQUIRE(...) \
52  THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
53
54#define TRY_ACQUIRE_SHARED(...) \
55  THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
56
57#define EXCLUDES(...) \
58  THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
59
60#define ASSERT_CAPABILITY(x) \
61  THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
62
63#define ASSERT_SHARED_CAPABILITY(x) \
64  THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
65
66#define RETURN_CAPABILITY(x) \
67  THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
68
69#define NO_THREAD_SAFETY_ANALYSIS \
70  THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
71
72
73namespace benchmark {
74
75typedef std::condition_variable Condition;
76
77// NOTE: Wrappers for std::mutex and std::unique_lock are provided so that
78// we can annotate them with thread safety attributes and use the
79// -Wthread-safety warning with clang. The standard library types cannot be
80// used directly because they do not provided the required annotations.
81class CAPABILITY("mutex") Mutex
82{
83public:
84  Mutex() {}
85
86  void lock() ACQUIRE() { mut_.lock(); }
87  void unlock() RELEASE() { mut_.unlock(); }
88  std::mutex& native_handle() {
89    return mut_;
90  }
91private:
92  std::mutex mut_;
93};
94
95
96class SCOPED_CAPABILITY MutexLock
97{
98  typedef std::unique_lock<std::mutex> MutexLockImp;
99public:
100  MutexLock(Mutex& m) ACQUIRE(m) : ml_(m.native_handle())
101  { }
102  ~MutexLock() RELEASE() {}
103  MutexLockImp& native_handle() { return ml_; }
104private:
105  MutexLockImp ml_;
106};
107
108
109class Notification
110{
111public:
112  Notification() : notified_yet_(false) { }
113
114  void WaitForNotification() const EXCLUDES(mutex_) {
115    MutexLock m_lock(mutex_);
116    auto notified_fn = [this]() REQUIRES(mutex_) {
117                            return this->HasBeenNotified();
118                        };
119    cv_.wait(m_lock.native_handle(), notified_fn);
120  }
121
122  void Notify() EXCLUDES(mutex_) {
123    {
124      MutexLock lock(mutex_);
125      notified_yet_ = 1;
126    }
127    cv_.notify_all();
128  }
129
130private:
131  bool HasBeenNotified() const REQUIRES(mutex_) {
132    return notified_yet_;
133  }
134
135  mutable Mutex mutex_;
136  mutable std::condition_variable cv_;
137  bool notified_yet_ GUARDED_BY(mutex_);
138};
139
140} // end namespace benchmark
141
142#endif // BENCHMARK_MUTEX_H_
trunk/3rdparty/benchmark/src/re.h
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef BENCHMARK_RE_H_
16#define BENCHMARK_RE_H_
17
18#if defined(HAVE_STD_REGEX)
19#include <regex>
20#elif defined(HAVE_GNU_POSIX_REGEX)
21#include <gnuregex.h>
22#elif defined(HAVE_POSIX_REGEX)
23#include <regex.h>
24#else
25#error No regular expression backend was found!
26#endif
27#include <string>
28
29namespace benchmark {
30
31// A wrapper around the POSIX regular expression API that provides automatic
32// cleanup
33class Regex {
34 public:
35  Regex();
36  ~Regex();
37
38  // Compile a regular expression matcher from spec.  Returns true on success.
39  //
40  // On failure (and if error is not nullptr), error is populated with a human
41  // readable error message if an error occurs.
42  bool Init(const std::string& spec, std::string* error);
43
44  // Returns whether str matches the compiled regular expression.
45  bool Match(const std::string& str);
46 private:
47  bool init_;
48  // Underlying regular expression object
49#if defined(HAVE_STD_REGEX)
50  std::regex re_;
51#elif defined(HAVE_POSIX_REGEX) || defined(HAVE_GNU_POSIX_REGEX)
52  regex_t re_;
53#else
54# error No regular expression backend implementation available
55#endif
56};
57
58}  // end namespace benchmark
59
60#endif  // BENCHMARK_RE_H_
trunk/3rdparty/benchmark/src/re_posix.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "check.h"
16#include "re.h"
17
18namespace benchmark {
19
20Regex::Regex() : init_(false) { }
21
22bool Regex::Init(const std::string& spec, std::string* error) {
23  int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB);
24  if (ec != 0) {
25    if (error) {
26      size_t needed = regerror(ec, &re_, nullptr, 0);
27      char* errbuf = new char[needed];
28      regerror(ec, &re_, errbuf, needed);
29
30      // regerror returns the number of bytes necessary to null terminate
31      // the string, so we move that when assigning to error.
32      CHECK_NE(needed, 0);
33      error->assign(errbuf, needed - 1);
34
35      delete[] errbuf;
36    }
37
38    return false;
39  }
40
41  init_ = true;
42  return true;
43}
44
45Regex::~Regex() {
46  if (init_) {
47    regfree(&re_);
48  }
49}
50
51bool Regex::Match(const std::string& str) {
52  if (!init_) {
53    return false;
54  }
55
56  return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0;
57}
58
59}  // end namespace benchmark
trunk/3rdparty/benchmark/src/re_std.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "re.h"
16
17namespace benchmark {
18
19Regex::Regex() : init_(false) { }
20
21bool Regex::Init(const std::string& spec, std::string* error) {
22  try {
23    re_ = std::regex(spec, std::regex_constants::extended);
24
25    init_ = true;
26  } catch (const std::regex_error& e) {
27    if (error) {
28      *error = e.what();
29    }
30  }
31  return init_;
32}
33
34Regex::~Regex() { }
35
36bool Regex::Match(const std::string& str) {
37  if (!init_) {
38    return false;
39  }
40
41  return std::regex_search(str, re_);
42}
43
44}  // end namespace benchmark
trunk/3rdparty/benchmark/src/reporter.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "benchmark/reporter.h"
16
17#include <cstdlib>
18#include <vector>
19
20#include "check.h"
21#include "stat.h"
22
23namespace benchmark {
24
25void BenchmarkReporter::ComputeStats(
26    const std::vector<Run>& reports,
27    Run* mean_data, Run* stddev_data) {
28  CHECK(reports.size() >= 2) << "Cannot compute stats for less than 2 reports";
29  // Accumulators.
30  Stat1_d real_accumulated_time_stat;
31  Stat1_d cpu_accumulated_time_stat;
32  Stat1_d bytes_per_second_stat;
33  Stat1_d items_per_second_stat;
34  // All repetitions should be run with the same number of iterations so we
35  // can take this information from the first benchmark.
36  int64_t const run_iterations = reports.front().iterations;
37
38  // Populate the accumulators.
39  for (Run const& run : reports) {
40    CHECK_EQ(reports[0].benchmark_name, run.benchmark_name);
41    CHECK_EQ(run_iterations, run.iterations);
42    real_accumulated_time_stat +=
43        Stat1_d(run.real_accumulated_time/run.iterations, run.iterations);
44    cpu_accumulated_time_stat +=
45        Stat1_d(run.cpu_accumulated_time/run.iterations, run.iterations);
46    items_per_second_stat += Stat1_d(run.items_per_second, run.iterations);
47    bytes_per_second_stat += Stat1_d(run.bytes_per_second, run.iterations);
48  }
49
50  // Get the data from the accumulator to BenchmarkReporter::Run's.
51  mean_data->benchmark_name = reports[0].benchmark_name + "_mean";
52  mean_data->iterations = run_iterations;
53  mean_data->real_accumulated_time = real_accumulated_time_stat.Mean() *
54                                     run_iterations;
55  mean_data->cpu_accumulated_time = cpu_accumulated_time_stat.Mean() *
56                                    run_iterations;
57  mean_data->bytes_per_second = bytes_per_second_stat.Mean();
58  mean_data->items_per_second = items_per_second_stat.Mean();
59
60  // Only add label to mean/stddev if it is same for all runs
61  mean_data->report_label = reports[0].report_label;
62  for (std::size_t i = 1; i < reports.size(); i++) {
63    if (reports[i].report_label != reports[0].report_label) {
64      mean_data->report_label = "";
65      break;
66    }
67  }
68
69  stddev_data->benchmark_name = reports[0].benchmark_name + "_stddev";
70  stddev_data->report_label = mean_data->report_label;
71  stddev_data->iterations = 0;
72  stddev_data->real_accumulated_time =
73      real_accumulated_time_stat.StdDev();
74  stddev_data->cpu_accumulated_time =
75      cpu_accumulated_time_stat.StdDev();
76  stddev_data->bytes_per_second = bytes_per_second_stat.StdDev();
77  stddev_data->items_per_second = items_per_second_stat.StdDev();
78}
79
80void BenchmarkReporter::Finalize() {
81}
82
83BenchmarkReporter::~BenchmarkReporter() {
84}
85
86} // end namespace benchmark
trunk/3rdparty/benchmark/src/sleep.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "sleep.h"
16
17#include <cerrno>
18#include <ctime>
19
20#include "internal_macros.h"
21
22#ifdef BENCHMARK_OS_WINDOWS
23#include <Windows.h>
24#endif
25
26namespace benchmark {
27#ifdef BENCHMARK_OS_WINDOWS
28// Window's Sleep takes milliseconds argument.
29void SleepForMilliseconds(int milliseconds) { Sleep(milliseconds); }
30void SleepForSeconds(double seconds) {
31  SleepForMilliseconds(static_cast<int>(kNumMillisPerSecond * seconds));
32}
33#else   // BENCHMARK_OS_WINDOWS
34void SleepForMicroseconds(int microseconds) {
35  struct timespec sleep_time;
36  sleep_time.tv_sec = microseconds / kNumMicrosPerSecond;
37  sleep_time.tv_nsec = (microseconds % kNumMicrosPerSecond) * kNumNanosPerMicro;
38  while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR)
39    ;  // Ignore signals and wait for the full interval to elapse.
40}
41
42void SleepForMilliseconds(int milliseconds) {
43  SleepForMicroseconds(static_cast<int>(milliseconds) * kNumMicrosPerMilli);
44}
45
46void SleepForSeconds(double seconds) {
47  SleepForMicroseconds(static_cast<int>(seconds * kNumMicrosPerSecond));
48}
49#endif  // BENCHMARK_OS_WINDOWS
50}  // end namespace benchmark
trunk/3rdparty/benchmark/src/sleep.h
r0r253077
1#ifndef BENCHMARK_SLEEP_H_
2#define BENCHMARK_SLEEP_H_
3
4#include <cstdint>
5
6namespace benchmark {
7const int64_t kNumMillisPerSecond = 1000LL;
8const int64_t kNumMicrosPerMilli = 1000LL;
9const int64_t kNumMicrosPerSecond = kNumMillisPerSecond * 1000LL;
10const int64_t kNumNanosPerMicro = 1000LL;
11const int64_t kNumNanosPerSecond = kNumNanosPerMicro * kNumMicrosPerSecond;
12
13void SleepForMilliseconds(int milliseconds);
14void SleepForSeconds(double seconds);
15}  // end namespace benchmark
16
17#endif  // BENCHMARK_SLEEP_H_
trunk/3rdparty/benchmark/src/stat.h
r0r253077
1#ifndef BENCHMARK_STAT_H_
2#define BENCHMARK_STAT_H_
3
4#include <cmath>
5#include <limits>
6#include <ostream>
7#include <type_traits>
8
9
10namespace benchmark {
11
12template <typename VType, typename NumType>
13class Stat1;
14
15template <typename VType, typename NumType>
16class Stat1MinMax;
17
18typedef Stat1<float, int64_t> Stat1_f;
19typedef Stat1<double, int64_t> Stat1_d;
20typedef Stat1MinMax<float, int64_t> Stat1MinMax_f;
21typedef Stat1MinMax<double, int64_t> Stat1MinMax_d;
22
23template <typename VType>
24class Vector2;
25template <typename VType>
26class Vector3;
27template <typename VType>
28class Vector4;
29
30template <typename VType, typename NumType>
31class Stat1 {
32 public:
33  typedef Stat1<VType, NumType> Self;
34
35  Stat1() { Clear(); }
36  // Create a sample of value dat and weight 1
37  explicit Stat1(const VType &dat) {
38    sum_ = dat;
39    sum_squares_ = Sqr(dat);
40    numsamples_ = 1;
41  }
42  // Create statistics for all the samples between begin (included)
43  // and end(excluded)
44  explicit Stat1(const VType *begin, const VType *end) {
45    Clear();
46    for (const VType *item = begin; item < end; ++item) {
47      (*this) += Stat1(*item);
48    }
49  }
50  // Create a sample of value dat and weight w
51  Stat1(const VType &dat, const NumType &w) {
52    sum_ = w * dat;
53    sum_squares_ = w * Sqr(dat);
54    numsamples_ = w;
55  }
56  // Copy operator
57  Stat1(const Self &stat) {
58    sum_ = stat.sum_;
59    sum_squares_ = stat.sum_squares_;
60    numsamples_ = stat.numsamples_;
61  }
62
63  void Clear() {
64    numsamples_ = NumType();
65    sum_squares_ = sum_ = VType();
66  }
67
68  Self &operator=(const Self &stat) {
69    sum_ = stat.sum_;
70    sum_squares_ = stat.sum_squares_;
71    numsamples_ = stat.numsamples_;
72    return (*this);
73  }
74  // Merge statistics from two sample sets.
75  Self &operator+=(const Self &stat) {
76    sum_ += stat.sum_;
77    sum_squares_ += stat.sum_squares_;
78    numsamples_ += stat.numsamples_;
79    return (*this);
80  }
81  // The operation opposite to +=
82  Self &operator-=(const Self &stat) {
83    sum_ -= stat.sum_;
84    sum_squares_ -= stat.sum_squares_;
85    numsamples_ -= stat.numsamples_;
86    return (*this);
87  }
88  // Multiply the weight of the set of samples by a factor k
89  Self &operator*=(const VType &k) {
90    sum_ *= k;
91    sum_squares_ *= k;
92    numsamples_ *= k;
93    return (*this);
94  }
95
96  // Merge statistics from two sample sets.
97  Self operator+(const Self &stat) const { return Self(*this) += stat; }
98
99  // The operation opposite to +
100  Self operator-(const Self &stat) const { return Self(*this) -= stat; }
101
102  // Multiply the weight of the set of samples by a factor k
103  Self operator*(const VType &k) const { return Self(*this) *= k; }
104
105  // Return the total weight of this sample set
106  NumType numSamples() const { return numsamples_; }
107
108  // Return the sum of this sample set
109  VType Sum() const { return sum_; }
110
111  // Return the mean of this sample set
112  VType Mean() const {
113    if (numsamples_ == 0) return VType();
114    return sum_ * (1.0 / numsamples_);
115  }
116
117  // Return the mean of this sample set and compute the standard deviation at
118  // the same time.
119  VType Mean(VType *stddev) const {
120    if (numsamples_ == 0) return VType();
121    VType mean = sum_ * (1.0 / numsamples_);
122    if (stddev) {
123      VType avg_squares = sum_squares_ * (1.0 / numsamples_);
124      *stddev = Sqrt(avg_squares - Sqr(mean));
125    }
126    return mean;
127  }
128
129  // Return the standard deviation of the sample set
130  VType StdDev() const {
131    if (numsamples_ == 0) return VType();
132    VType mean = Mean();
133    VType avg_squares = sum_squares_ * (1.0 / numsamples_);
134    return Sqrt(avg_squares - Sqr(mean));
135  }
136
137 private:
138  static_assert(std::is_integral<NumType>::value &&
139                !std::is_same<NumType, bool>::value,
140                "NumType must be an integral type that is not bool.");
141  // Let i be the index of the samples provided (using +=)
142  // and weight[i],value[i] be the data of sample #i
143  // then the variables have the following meaning:
144  NumType numsamples_;  // sum of weight[i];
145  VType sum_;           // sum of weight[i]*value[i];
146  VType sum_squares_;   // sum of weight[i]*value[i]^2;
147
148  // Template function used to square a number.
149  // For a vector we square all components
150  template <typename SType>
151  static inline SType Sqr(const SType &dat) {
152    return dat * dat;
153  }
154
155  template <typename SType>
156  static inline Vector2<SType> Sqr(const Vector2<SType> &dat) {
157    return dat.MulComponents(dat);
158  }
159
160  template <typename SType>
161  static inline Vector3<SType> Sqr(const Vector3<SType> &dat) {
162    return dat.MulComponents(dat);
163  }
164
165  template <typename SType>
166  static inline Vector4<SType> Sqr(const Vector4<SType> &dat) {
167    return dat.MulComponents(dat);
168  }
169
170  // Template function used to take the square root of a number.
171  // For a vector we square all components
172  template <typename SType>
173  static inline SType Sqrt(const SType &dat) {
174    // Avoid NaN due to imprecision in the calculations
175    if (dat < 0) return 0;
176    return sqrt(dat);
177  }
178
179  template <typename SType>
180  static inline Vector2<SType> Sqrt(const Vector2<SType> &dat) {
181    // Avoid NaN due to imprecision in the calculations
182    return Max(dat, Vector2<SType>()).Sqrt();
183  }
184
185  template <typename SType>
186  static inline Vector3<SType> Sqrt(const Vector3<SType> &dat) {
187    // Avoid NaN due to imprecision in the calculations
188    return Max(dat, Vector3<SType>()).Sqrt();
189  }
190
191  template <typename SType>
192  static inline Vector4<SType> Sqrt(const Vector4<SType> &dat) {
193    // Avoid NaN due to imprecision in the calculations
194    return Max(dat, Vector4<SType>()).Sqrt();
195  }
196};
197
198// Useful printing function
199template <typename VType, typename NumType>
200std::ostream &operator<<(std::ostream &out, const Stat1<VType, NumType> &s) {
201  out << "{ avg = " << s.Mean() << " std = " << s.StdDev()
202      << " nsamples = " << s.NumSamples() << "}";
203  return out;
204}
205
206// Stat1MinMax: same as Stat1, but it also
207// keeps the Min and Max values; the "-"
208// operator is disabled because it cannot be implemented
209// efficiently
210template <typename VType, typename NumType>
211class Stat1MinMax : public Stat1<VType, NumType> {
212 public:
213  typedef Stat1MinMax<VType, NumType> Self;
214
215  Stat1MinMax() { Clear(); }
216  // Create a sample of value dat and weight 1
217  explicit Stat1MinMax(const VType &dat) : Stat1<VType, NumType>(dat) {
218    max_ = dat;
219    min_ = dat;
220  }
221  // Create statistics for all the samples between begin (included)
222  // and end(excluded)
223  explicit Stat1MinMax(const VType *begin, const VType *end) {
224    Clear();
225    for (const VType *item = begin; item < end; ++item) {
226      (*this) += Stat1MinMax(*item);
227    }
228  }
229  // Create a sample of value dat and weight w
230  Stat1MinMax(const VType &dat, const NumType &w)
231      : Stat1<VType, NumType>(dat, w) {
232    max_ = dat;
233    min_ = dat;
234  }
235  // Copy operator
236  Stat1MinMax(const Self &stat) : Stat1<VType, NumType>(stat) {
237    max_ = stat.max_;
238    min_ = stat.min_;
239  }
240
241  void Clear() {
242    Stat1<VType, NumType>::Clear();
243    if (std::numeric_limits<VType>::has_infinity) {
244      min_ = std::numeric_limits<VType>::infinity();
245      max_ = -std::numeric_limits<VType>::infinity();
246    } else {
247      min_ = std::numeric_limits<VType>::max();
248      max_ = std::numeric_limits<VType>::min();
249    }
250  }
251
252  Self &operator=(const Self &stat) {
253    this->Stat1<VType, NumType>::operator=(stat);
254    max_ = stat.max_;
255    min_ = stat.min_;
256    return (*this);
257  }
258  // Merge statistics from two sample sets.
259  Self &operator+=(const Self &stat) {
260    this->Stat1<VType, NumType>::operator+=(stat);
261    if (stat.max_ > max_) max_ = stat.max_;
262    if (stat.min_ < min_) min_ = stat.min_;
263    return (*this);
264  }
265  // Multiply the weight of the set of samples by a factor k
266  Self &operator*=(const VType &stat) {
267    this->Stat1<VType, NumType>::operator*=(stat);
268    return (*this);
269  }
270  // Merge statistics from two sample sets.
271  Self operator+(const Self &stat) const { return Self(*this) += stat; }
272  // Multiply the weight of the set of samples by a factor k
273  Self operator*(const VType &k) const { return Self(*this) *= k; }
274
275  // Return the maximal value in this sample set
276  VType Max() const { return max_; }
277  // Return the minimal value in this sample set
278  VType Min() const { return min_; }
279
280 private:
281  // The - operation makes no sense with Min/Max
282  // unless we keep the full list of values (but we don't)
283  // make it private, and let it undefined so nobody can call it
284  Self &operator-=(const Self &stat);  // senseless. let it undefined.
285
286  // The operation opposite to -
287  Self operator-(const Self &stat) const;  // senseless. let it undefined.
288
289  // Let i be the index of the samples provided (using +=)
290  // and weight[i],value[i] be the data of sample #i
291  // then the variables have the following meaning:
292  VType max_;  // max of value[i]
293  VType min_;  // min of value[i]
294};
295
296// Useful printing function
297template <typename VType, typename NumType>
298std::ostream &operator<<(std::ostream &out,
299                         const Stat1MinMax<VType, NumType> &s) {
300  out << "{ avg = " << s.Mean() << " std = " << s.StdDev()
301      << " nsamples = " << s.NumSamples() << " min = " << s.Min()
302      << " max = " << s.Max() << "}";
303  return out;
304}
305}  // end namespace benchmark
306
307#endif  // BENCHMARK_STAT_H_
trunk/3rdparty/benchmark/src/string_util.cc
r0r253077
1#include "string_util.h"
2
3#include <cmath>
4#include <cstdarg>
5#include <array>
6#include <memory>
7#include <sstream>
8#include <stdio.h>
9
10#include "arraysize.h"
11
12namespace benchmark {
13namespace {
14
15// kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta.
16const char kBigSIUnits[] = "kMGTPEZY";
17// Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi.
18const char kBigIECUnits[] = "KMGTPEZY";
19// milli, micro, nano, pico, femto, atto, zepto, yocto.
20const char kSmallSIUnits[] = "munpfazy";
21
22// We require that all three arrays have the same size.
23static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits),
24              "SI and IEC unit arrays must be the same size");
25static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits),
26              "Small SI and Big SI unit arrays must be the same size");
27
28static const int64_t kUnitsSize = arraysize(kBigSIUnits);
29
30} // end anonymous namespace
31
32void ToExponentAndMantissa(double val, double thresh, int precision,
33                           double one_k, std::string* mantissa,
34                           int64_t* exponent) {
35  std::stringstream mantissa_stream;
36
37  if (val < 0) {
38    mantissa_stream << "-";
39    val = -val;
40  }
41
42  // Adjust threshold so that it never excludes things which can't be rendered
43  // in 'precision' digits.
44  const double adjusted_threshold =
45      std::max(thresh, 1.0 / std::pow(10.0, precision));
46  const double big_threshold = adjusted_threshold * one_k;
47  const double small_threshold = adjusted_threshold;
48
49  if (val > big_threshold) {
50    // Positive powers
51    double scaled = val;
52    for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) {
53      scaled /= one_k;
54      if (scaled <= big_threshold) {
55        mantissa_stream << scaled;
56        *exponent = i + 1;
57        *mantissa = mantissa_stream.str();
58        return;
59      }
60    }
61    mantissa_stream << val;
62    *exponent = 0;
63  } else if (val < small_threshold) {
64    // Negative powers
65    double scaled = val;
66    for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) {
67      scaled *= one_k;
68      if (scaled >= small_threshold) {
69        mantissa_stream << scaled;
70        *exponent = -static_cast<int64_t>(i + 1);
71        *mantissa = mantissa_stream.str();
72        return;
73      }
74    }
75    mantissa_stream << val;
76    *exponent = 0;
77  } else {
78    mantissa_stream << val;
79    *exponent = 0;
80  }
81  *mantissa = mantissa_stream.str();
82}
83
84std::string ExponentToPrefix(int64_t exponent, bool iec) {
85  if (exponent == 0) return "";
86
87  const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1);
88  if (index >= kUnitsSize) return "";
89
90  const char* array =
91      (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits);
92  if (iec)
93    return array[index] + std::string("i");
94  else
95    return std::string(1, array[index]);
96}
97
98std::string ToBinaryStringFullySpecified(double value, double threshold,
99                                         int precision) {
100  std::string mantissa;
101  int64_t exponent;
102  ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa,
103                        &exponent);
104  return mantissa + ExponentToPrefix(exponent, false);
105}
106
107void AppendHumanReadable(int n, std::string* str) {
108  std::stringstream ss;
109  // Round down to the nearest SI prefix.
110  ss << "/" << ToBinaryStringFullySpecified(n, 1.0, 0);
111  *str += ss.str();
112}
113
114std::string HumanReadableNumber(double n) {
115  // 1.1 means that figures up to 1.1k should be shown with the next unit down;
116  // this softens edge effects.
117  // 1 means that we should show one decimal place of precision.
118  return ToBinaryStringFullySpecified(n, 1.1, 1);
119}
120
121std::string StringPrintFImp(const char *msg, va_list args)
122{
123  // we might need a second shot at this, so pre-emptivly make a copy
124  va_list args_cp;
125  va_copy(args_cp, args);
126
127  // TODO(ericwf): use std::array for first attempt to avoid one memory
128  // allocation guess what the size might be
129  std::array<char, 256> local_buff;
130  std::size_t size = local_buff.size();
131  // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation in the android-ndk
132  auto ret = vsnprintf(local_buff.data(), size, msg, args_cp);
133
134  va_end(args_cp);
135
136  // handle empty expansion
137  if (ret == 0)
138    return std::string{};
139  if (static_cast<std::size_t>(ret) < size)
140    return std::string(local_buff.data());
141
142  // we did not provide a long enough buffer on our first attempt.
143  // add 1 to size to account for null-byte in size cast to prevent overflow
144  size = static_cast<std::size_t>(ret) + 1;
145  auto buff_ptr = std::unique_ptr<char[]>(new char[size]);
146  // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation in the android-ndk
147  ret = vsnprintf(buff_ptr.get(), size, msg, args);
148  return std::string(buff_ptr.get());
149}
150
151std::string StringPrintF(const char* format, ...)
152{
153  va_list args;
154  va_start(args, format);
155  std::string tmp = StringPrintFImp(format, args);
156  va_end(args);
157  return tmp;
158}
159
160void ReplaceAll(std::string* str, const std::string& from,
161                const std::string& to) {
162  std::size_t start = 0;
163  while((start = str->find(from, start)) != std::string::npos) {
164    str->replace(start, from.length(), to);
165    start += to.length();
166  }
167}
168
169} // end namespace benchmark
trunk/3rdparty/benchmark/src/string_util.h
r0r253077
1#ifndef BENCHMARK_STRING_UTIL_H_
2#define BENCHMARK_STRING_UTIL_H_
3
4#include <string>
5#include <sstream>
6#include <utility>
7#include "internal_macros.h"
8
9namespace benchmark {
10
11void AppendHumanReadable(int n, std::string* str);
12
13std::string HumanReadableNumber(double n);
14
15std::string StringPrintF(const char* format, ...);
16
17inline std::ostream&
18StringCatImp(std::ostream& out) BENCHMARK_NOEXCEPT
19{
20  return out;
21}
22
23template <class First, class ...Rest>
24inline std::ostream&
25StringCatImp(std::ostream& out, First&& f, Rest&&... rest)
26{
27  out << std::forward<First>(f);
28  return StringCatImp(out, std::forward<Rest>(rest)...);
29}
30
31template<class ...Args>
32inline std::string StrCat(Args&&... args)
33{
34  std::ostringstream ss;
35  StringCatImp(ss, std::forward<Args>(args)...);
36  return ss.str();
37}
38
39void ReplaceAll(std::string* str, const std::string& from,
40                const std::string& to);
41
42} // end namespace benchmark
43
44#endif // BENCHMARK_STRING_UTIL_H_
trunk/3rdparty/benchmark/src/sysinfo.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "sysinfo.h"
16#include "internal_macros.h"
17
18#ifdef BENCHMARK_OS_WINDOWS
19#include <Shlwapi.h>
20#include <Windows.h>
21#include <VersionHelpers.h>
22#else
23#include <fcntl.h>
24#include <sys/resource.h>
25#include <sys/types.h> // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD
26#include <sys/time.h>
27#include <unistd.h>
28#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX
29#include <sys/sysctl.h>
30#endif
31#endif
32
33#include <cerrno>
34#include <cstdio>
35#include <cstdint>
36#include <cstdlib>
37#include <cstring>
38#include <iostream>
39#include <limits>
40#include <mutex>
41
42#include "arraysize.h"
43#include "check.h"
44#include "cycleclock.h"
45#include "internal_macros.h"
46#include "log.h"
47#include "sleep.h"
48#include "string_util.h"
49
50namespace benchmark {
51namespace {
52std::once_flag cpuinfo_init;
53double cpuinfo_cycles_per_second = 1.0;
54int cpuinfo_num_cpus = 1;  // Conservative guess
55std::mutex cputimens_mutex;
56
57#if !defined BENCHMARK_OS_MACOSX
58const int64_t estimate_time_ms = 1000;
59
60// Helper function estimates cycles/sec by observing cycles elapsed during
61// sleep(). Using small sleep time decreases accuracy significantly.
62int64_t EstimateCyclesPerSecond() {
63  const int64_t start_ticks = cycleclock::Now();
64  SleepForMilliseconds(estimate_time_ms);
65  return cycleclock::Now() - start_ticks;
66}
67#endif
68
69#if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN
70// Helper function for reading an int from a file. Returns true if successful
71// and the memory location pointed to by value is set to the value read.
72bool ReadIntFromFile(const char* file, long* value) {
73  bool ret = false;
74  int fd = open(file, O_RDONLY);
75  if (fd != -1) {
76    char line[1024];
77    char* err;
78    memset(line, '\0', sizeof(line));
79    CHECK(read(fd, line, sizeof(line) - 1));
80    const long temp_value = strtol(line, &err, 10);
81    if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
82      *value = temp_value;
83      ret = true;
84    }
85    close(fd);
86  }
87  return ret;
88}
89#endif
90
91void InitializeSystemInfo() {
92#if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN
93  char line[1024];
94  char* err;
95  long freq;
96
97  bool saw_mhz = false;
98
99  // If the kernel is exporting the tsc frequency use that. There are issues
100  // where cpuinfo_max_freq cannot be relied on because the BIOS may be
101  // exporintg an invalid p-state (on x86) or p-states may be used to put the
102  // processor in a new mode (turbo mode). Essentially, those frequencies
103  // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as
104  // well.
105  if (!saw_mhz &&
106      ReadIntFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) {
107    // The value is in kHz (as the file name suggests).  For example, on a
108    // 2GHz warpstation, the file contains the value "2000000".
109    cpuinfo_cycles_per_second = freq * 1000.0;
110    saw_mhz = true;
111  }
112
113  // If CPU scaling is in effect, we want to use the *maximum* frequency,
114  // not whatever CPU speed some random processor happens to be using now.
115  if (!saw_mhz &&
116      ReadIntFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
117                      &freq)) {
118    // The value is in kHz.  For example, on a 2GHz warpstation, the file
119    // contains the value "2000000".
120    cpuinfo_cycles_per_second = freq * 1000.0;
121    saw_mhz = true;
122  }
123
124  // Read /proc/cpuinfo for other values, and if there is no cpuinfo_max_freq.
125  const char* pname = "/proc/cpuinfo";
126  int fd = open(pname, O_RDONLY);
127  if (fd == -1) {
128    perror(pname);
129    if (!saw_mhz) {
130      cpuinfo_cycles_per_second = static_cast<double>(EstimateCyclesPerSecond());
131    }
132    return;
133  }
134
135  double bogo_clock = 1.0;
136  bool saw_bogo = false;
137  long max_cpu_id = 0;
138  int num_cpus = 0;
139  line[0] = line[1] = '\0';
140  size_t chars_read = 0;
141  do {  // we'll exit when the last read didn't read anything
142    // Move the next line to the beginning of the buffer
143    const size_t oldlinelen = strlen(line);
144    if (sizeof(line) == oldlinelen + 1)  // oldlinelen took up entire line
145      line[0] = '\0';
146    else  // still other lines left to save
147      memmove(line, line + oldlinelen + 1, sizeof(line) - (oldlinelen + 1));
148    // Terminate the new line, reading more if we can't find the newline
149    char* newline = strchr(line, '\n');
150    if (newline == nullptr) {
151      const size_t linelen = strlen(line);
152      const size_t bytes_to_read = sizeof(line) - 1 - linelen;
153      CHECK(bytes_to_read > 0);  // because the memmove recovered >=1 bytes
154      chars_read = read(fd, line + linelen, bytes_to_read);
155      line[linelen + chars_read] = '\0';
156      newline = strchr(line, '\n');
157    }
158    if (newline != nullptr) *newline = '\0';
159
160    // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only
161    // accept postive values. Some environments (virtual machines) report zero,
162    // which would cause infinite looping in WallTime_Init.
163    if (!saw_mhz && strncasecmp(line, "cpu MHz", sizeof("cpu MHz") - 1) == 0) {
164      const char* freqstr = strchr(line, ':');
165      if (freqstr) {
166        cpuinfo_cycles_per_second = strtod(freqstr + 1, &err) * 1000000.0;
167        if (freqstr[1] != '\0' && *err == '\0' && cpuinfo_cycles_per_second > 0)
168          saw_mhz = true;
169      }
170    } else if (strncasecmp(line, "bogomips", sizeof("bogomips") - 1) == 0) {
171      const char* freqstr = strchr(line, ':');
172      if (freqstr) {
173        bogo_clock = strtod(freqstr + 1, &err) * 1000000.0;
174        if (freqstr[1] != '\0' && *err == '\0' && bogo_clock > 0)
175          saw_bogo = true;
176      }
177    } else if (strncasecmp(line, "processor", sizeof("processor") - 1) == 0) {
178      num_cpus++;  // count up every time we see an "processor :" entry
179      const char* freqstr = strchr(line, ':');
180      if (freqstr) {
181        const long cpu_id = strtol(freqstr + 1, &err, 10);
182        if (freqstr[1] != '\0' && *err == '\0' && max_cpu_id < cpu_id)
183          max_cpu_id = cpu_id;
184      }
185    }
186  } while (chars_read > 0);
187  close(fd);
188
189  if (!saw_mhz) {
190    if (saw_bogo) {
191      // If we didn't find anything better, we'll use bogomips, but
192      // we're not happy about it.
193      cpuinfo_cycles_per_second = bogo_clock;
194    } else {
195      // If we don't even have bogomips, we'll use the slow estimation.
196      cpuinfo_cycles_per_second = static_cast<double>(EstimateCyclesPerSecond());
197    }
198  }
199  if (num_cpus == 0) {
200    fprintf(stderr, "Failed to read num. CPUs correctly from /proc/cpuinfo\n");
201  } else {
202    if ((max_cpu_id + 1) != num_cpus) {
203      fprintf(stderr,
204              "CPU ID assignments in /proc/cpuinfo seems messed up."
205              " This is usually caused by a bad BIOS.\n");
206    }
207    cpuinfo_num_cpus = num_cpus;
208  }
209
210#elif defined BENCHMARK_OS_FREEBSD
211// For this sysctl to work, the machine must be configured without
212// SMP, APIC, or APM support.  hz should be 64-bit in freebsd 7.0
213// and later.  Before that, it's a 32-bit quantity (and gives the
214// wrong answer on machines faster than 2^32 Hz).  See
215//  http://lists.freebsd.org/pipermail/freebsd-i386/2004-November/001846.html
216// But also compare FreeBSD 7.0:
217//  http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG70#L223
218//  231         error = sysctl_handle_quad(oidp, &freq, 0, req);
219// To FreeBSD 6.3 (it's the same in 6-STABLE):
220//  http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG6#L131
221//  139         error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
222#if __FreeBSD__ >= 7
223  uint64_t hz = 0;
224#else
225  unsigned int hz = 0;
226#endif
227  size_t sz = sizeof(hz);
228  const char* sysctl_path = "machdep.tsc_freq";
229  if (sysctlbyname(sysctl_path, &hz, &sz, nullptr, 0) != 0) {
230    fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n",
231            sysctl_path, strerror(errno));
232    cpuinfo_cycles_per_second = static_cast<double>(EstimateCyclesPerSecond());
233  } else {
234    cpuinfo_cycles_per_second = hz;
235  }
236// TODO: also figure out cpuinfo_num_cpus
237
238#elif defined BENCHMARK_OS_WINDOWS
239  // In NT, read MHz from the registry. If we fail to do so or we're in win9x
240  // then make a crude estimate.
241  DWORD data, data_size = sizeof(data);
242  if (IsWindowsXPOrGreater() &&
243      SUCCEEDED(
244          SHGetValueA(HKEY_LOCAL_MACHINE,
245                      "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
246                      "~MHz", nullptr, &data, &data_size)))
247    cpuinfo_cycles_per_second = static_cast<double>((int64_t)data * (int64_t)(1000 * 1000));  // was mhz
248  else
249    cpuinfo_cycles_per_second = static_cast<double>(EstimateCyclesPerSecond());
250// TODO: also figure out cpuinfo_num_cpus
251
252#elif defined BENCHMARK_OS_MACOSX
253  // returning "mach time units" per second. the current number of elapsed
254  // mach time units can be found by calling uint64 mach_absolute_time();
255  // while not as precise as actual CPU cycles, it is accurate in the face
256  // of CPU frequency scaling and multi-cpu/core machines.
257  // Our mac users have these types of machines, and accuracy
258  // (i.e. correctness) trumps precision.
259  // See cycleclock.h: CycleClock::Now(), which returns number of mach time
260  // units on Mac OS X.
261  mach_timebase_info_data_t timebase_info;
262  mach_timebase_info(&timebase_info);
263  double mach_time_units_per_nanosecond =
264      static_cast<double>(timebase_info.denom) /
265      static_cast<double>(timebase_info.numer);
266  cpuinfo_cycles_per_second = mach_time_units_per_nanosecond * 1e9;
267
268  int num_cpus = 0;
269  size_t size = sizeof(num_cpus);
270  int numcpus_name[] = {CTL_HW, HW_NCPU};
271  if (::sysctl(numcpus_name, arraysize(numcpus_name), &num_cpus, &size, nullptr, 0) ==
272          0 &&
273      (size == sizeof(num_cpus)))
274    cpuinfo_num_cpus = num_cpus;
275
276#else
277  // Generic cycles per second counter
278  cpuinfo_cycles_per_second = static_cast<double>(EstimateCyclesPerSecond());
279#endif
280}
281}  // end namespace
282
283// getrusage() based implementation of MyCPUUsage
284static double MyCPUUsageRUsage() {
285#ifndef BENCHMARK_OS_WINDOWS
286  struct rusage ru;
287  if (getrusage(RUSAGE_SELF, &ru) == 0) {
288    return (static_cast<double>(ru.ru_utime.tv_sec) +
289            static_cast<double>(ru.ru_utime.tv_usec) * 1e-6 +
290            static_cast<double>(ru.ru_stime.tv_sec) +
291            static_cast<double>(ru.ru_stime.tv_usec) * 1e-6);
292  } else {
293    return 0.0;
294  }
295#else
296  HANDLE proc = GetCurrentProcess();
297  FILETIME creation_time;
298  FILETIME exit_time;
299  FILETIME kernel_time;
300  FILETIME user_time;
301  ULARGE_INTEGER kernel;
302  ULARGE_INTEGER user;
303  GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time, &user_time);
304  kernel.HighPart = kernel_time.dwHighDateTime;
305  kernel.LowPart = kernel_time.dwLowDateTime;
306  user.HighPart = user_time.dwHighDateTime;
307  user.LowPart = user_time.dwLowDateTime;
308  return (static_cast<double>(kernel.QuadPart) +
309          static_cast<double>(user.QuadPart)) * 1e-7;
310#endif  // OS_WINDOWS
311}
312
313#ifndef BENCHMARK_OS_WINDOWS
314static bool MyCPUUsageCPUTimeNsLocked(double* cputime) {
315  static int cputime_fd = -1;
316  if (cputime_fd == -1) {
317    cputime_fd = open("/proc/self/cputime_ns", O_RDONLY);
318    if (cputime_fd < 0) {
319      cputime_fd = -1;
320      return false;
321    }
322  }
323  char buff[64];
324  memset(buff, 0, sizeof(buff));
325  if (pread(cputime_fd, buff, sizeof(buff) - 1, 0) <= 0) {
326    close(cputime_fd);
327    cputime_fd = -1;
328    return false;
329  }
330  unsigned long long result = strtoull(buff, nullptr, 0);
331  if (result == (std::numeric_limits<unsigned long long>::max)()) {
332    close(cputime_fd);
333    cputime_fd = -1;
334    return false;
335  }
336  *cputime = static_cast<double>(result) / 1e9;
337  return true;
338}
339#endif  // OS_WINDOWS
340
341double MyCPUUsage() {
342#ifndef BENCHMARK_OS_WINDOWS
343  {
344    std::lock_guard<std::mutex> l(cputimens_mutex);
345    static bool use_cputime_ns = true;
346    if (use_cputime_ns) {
347      double value;
348      if (MyCPUUsageCPUTimeNsLocked(&value)) {
349        return value;
350      }
351      // Once MyCPUUsageCPUTimeNsLocked fails once fall back to getrusage().
352      VLOG(1) << "Reading /proc/self/cputime_ns failed. Using getrusage().\n";
353      use_cputime_ns = false;
354    }
355  }
356#endif  // OS_WINDOWS
357  return MyCPUUsageRUsage();
358}
359
360double ChildrenCPUUsage() {
361#ifndef BENCHMARK_OS_WINDOWS
362  struct rusage ru;
363  if (getrusage(RUSAGE_CHILDREN, &ru) == 0) {
364    return (static_cast<double>(ru.ru_utime.tv_sec) +
365            static_cast<double>(ru.ru_utime.tv_usec) * 1e-6 +
366            static_cast<double>(ru.ru_stime.tv_sec) +
367            static_cast<double>(ru.ru_stime.tv_usec) * 1e-6);
368  } else {
369    return 0.0;
370  }
371#else
372  // TODO: Not sure what this even means on Windows
373  return 0.0;
374#endif  // OS_WINDOWS
375}
376
377double CyclesPerSecond(void) {
378  std::call_once(cpuinfo_init, InitializeSystemInfo);
379  return cpuinfo_cycles_per_second;
380}
381
382int NumCPUs(void) {
383  std::call_once(cpuinfo_init, InitializeSystemInfo);
384  return cpuinfo_num_cpus;
385}
386
387// The ""'s catch people who don't pass in a literal for "str"
388#define strliterallen(str) (sizeof("" str "") - 1)
389
390// Must use a string literal for prefix.
391#define memprefix(str, len, prefix)                       \
392  ((((len) >= strliterallen(prefix)) &&                   \
393    std::memcmp(str, prefix, strliterallen(prefix)) == 0) \
394       ? str + strliterallen(prefix)                      \
395       : nullptr)
396
397bool CpuScalingEnabled() {
398#ifndef BENCHMARK_OS_WINDOWS
399  // On Linux, the CPUfreq subsystem exposes CPU information as files on the
400  // local file system. If reading the exported files fails, then we may not be
401  // running on Linux, so we silently ignore all the read errors.
402  for (int cpu = 0, num_cpus = NumCPUs(); cpu < num_cpus; ++cpu) {
403    std::string governor_file = StrCat("/sys/devices/system/cpu/cpu", cpu,
404                                       "/cpufreq/scaling_governor");
405    FILE* file = fopen(governor_file.c_str(), "r");
406    if (!file) break;
407    char buff[16];
408    size_t bytes_read = fread(buff, 1, sizeof(buff), file);
409    fclose(file);
410    if (memprefix(buff, bytes_read, "performance") == nullptr) return true;
411  }
412#endif
413  return false;
414}
415
416}  // end namespace benchmark
trunk/3rdparty/benchmark/src/sysinfo.h
r0r253077
1#ifndef BENCHMARK_SYSINFO_H_
2#define BENCHMARK_SYSINFO_H_
3
4namespace benchmark {
5double MyCPUUsage();
6double ChildrenCPUUsage();
7int NumCPUs();
8double CyclesPerSecond();
9bool CpuScalingEnabled();
10}  // end namespace benchmark
11
12#endif  // BENCHMARK_SYSINFO_H_
trunk/3rdparty/benchmark/src/walltime.cc
r0r253077
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "benchmark/macros.h"
16#include "internal_macros.h"
17#include "walltime.h"
18
19#if defined(BENCHMARK_OS_WINDOWS)
20#include <time.h>
21#include <winsock.h> // for timeval
22#else
23#include <sys/time.h>
24#endif
25
26#include <cstdio>
27#include <cstdint>
28#include <cstring>
29#include <ctime>
30
31#include <atomic>
32#include <chrono>
33#include <limits>
34
35#include "arraysize.h"
36#include "check.h"
37#include "cycleclock.h"
38#include "log.h"
39#include "sysinfo.h"
40
41namespace benchmark {
42namespace walltime {
43
44namespace {
45
46#if defined(HAVE_STEADY_CLOCK)
47template <bool HighResIsSteady = std::chrono::high_resolution_clock::is_steady>
48struct ChooseSteadyClock {
49    typedef std::chrono::high_resolution_clock type;
50};
51
52template <>
53struct ChooseSteadyClock<false> {
54    typedef std::chrono::steady_clock type;
55};
56#endif
57
58struct ChooseClockType {
59#if defined(HAVE_STEADY_CLOCK)
60  typedef ChooseSteadyClock<>::type type;
61#else
62  typedef std::chrono::high_resolution_clock type;
63#endif
64};
65
66class WallTimeImp
67{
68public:
69  WallTime Now();
70
71  static WallTimeImp& GetWallTimeImp() {
72    static WallTimeImp* imp = new WallTimeImp();
73    return *imp;
74  }
75
76private:
77  WallTimeImp();
78  // Helper routines to load/store a float from an AtomicWord. Required because
79  // g++ < 4.7 doesn't support std::atomic<float> correctly. I cannot wait to
80  // get rid of this horror show.
81  void SetDrift(float f) {
82    int32_t w;
83    memcpy(&w, &f, sizeof(f));
84    std::atomic_store(&drift_adjust_, w);
85  }
86
87  float GetDrift() const {
88    float f;
89    int32_t w = std::atomic_load(&drift_adjust_);
90    memcpy(&f, &w, sizeof(f));
91    return f;
92  }
93
94  WallTime Slow() const {
95    struct timeval tv;
96#if defined(BENCHMARK_OS_WINDOWS)
97    FILETIME    file_time;
98    SYSTEMTIME  system_time;
99    ULARGE_INTEGER ularge;
100    const unsigned __int64 epoch = 116444736000000000LL;
101
102    GetSystemTime(&system_time);
103    SystemTimeToFileTime(&system_time, &file_time);
104    ularge.LowPart = file_time.dwLowDateTime;
105    ularge.HighPart = file_time.dwHighDateTime;
106
107    tv.tv_sec = (long)((ularge.QuadPart - epoch) / (10L * 1000 * 1000));
108    tv.tv_usec = (long)(system_time.wMilliseconds * 1000);
109#else
110    gettimeofday(&tv, nullptr);
111#endif
112    return tv.tv_sec + tv.tv_usec * 1e-6;
113  }
114
115private:
116  static_assert(sizeof(float) <= sizeof(int32_t),
117               "type sizes don't allow the drift_adjust hack");
118
119  WallTime base_walltime_;
120  int64_t base_cycletime_;
121  int64_t cycles_per_second_;
122  double seconds_per_cycle_;
123  uint32_t last_adjust_time_;
124  std::atomic<int32_t> drift_adjust_;
125  int64_t max_interval_cycles_;
126
127  BENCHMARK_DISALLOW_COPY_AND_ASSIGN(WallTimeImp);
128};
129
130
131WallTime WallTimeImp::Now() {
132  WallTime now = 0.0;
133  WallTime result = 0.0;
134  int64_t ct = 0;
135  uint32_t top_bits = 0;
136  do {
137    ct = cycleclock::Now();
138    int64_t cycle_delta = ct - base_cycletime_;
139    result = base_walltime_ + cycle_delta * seconds_per_cycle_;
140
141    top_bits = static_cast<uint32_t>(uint64_t(ct) >> 32);
142    // Recompute drift no more often than every 2^32 cycles.
143    // I.e., @2GHz, ~ every two seconds
144    if (top_bits == last_adjust_time_) {  // don't need to recompute drift
145      return result + GetDrift();
146    }
147
148    now = Slow();
149  } while (cycleclock::Now() - ct > max_interval_cycles_);
150  // We are now sure that "now" and "result" were produced within
151  // kMaxErrorInterval of one another.
152
153  SetDrift(static_cast<float>(now - result));
154  last_adjust_time_ = top_bits;
155  return now;
156}
157
158
159WallTimeImp::WallTimeImp()
160    : base_walltime_(0.0), base_cycletime_(0),
161      cycles_per_second_(0), seconds_per_cycle_(0.0),
162      last_adjust_time_(0), drift_adjust_(0),
163      max_interval_cycles_(0) {
164  const double kMaxErrorInterval = 100e-6;
165  cycles_per_second_ = static_cast<int64_t>(CyclesPerSecond());
166  CHECK(cycles_per_second_ != 0);
167  seconds_per_cycle_ = 1.0 / cycles_per_second_;
168  max_interval_cycles_ =
169      static_cast<int64_t>(cycles_per_second_ * kMaxErrorInterval);
170  do {
171    base_cycletime_ = cycleclock::Now();
172    base_walltime_ = Slow();
173  } while (cycleclock::Now() - base_cycletime_ > max_interval_cycles_);
174  // We are now sure that "base_walltime" and "base_cycletime" were produced
175  // within kMaxErrorInterval of one another.
176
177  SetDrift(0.0);
178  last_adjust_time_ = static_cast<uint32_t>(uint64_t(base_cycletime_) >> 32);
179}
180
181WallTime CPUWalltimeNow() {
182  static WallTimeImp& imp = WallTimeImp::GetWallTimeImp();
183  return imp.Now();
184}
185
186WallTime ChronoWalltimeNow() {
187  typedef ChooseClockType::type Clock;
188  typedef std::chrono::duration<WallTime, std::chrono::seconds::period>
189          FPSeconds;
190  static_assert(std::chrono::treat_as_floating_point<WallTime>::value,
191                "This type must be treated as a floating point type.");
192  auto now = Clock::now().time_since_epoch();
193  return std::chrono::duration_cast<FPSeconds>(now).count();
194}
195
196bool UseCpuCycleClock() {
197    bool useWallTime = !CpuScalingEnabled();
198    if (useWallTime) {
199        VLOG(1) << "Using the CPU cycle clock to provide walltime::Now().\n";
200    } else {
201        VLOG(1) << "Using std::chrono to provide walltime::Now().\n";
202    }
203    return useWallTime;
204}
205
206
207} // end anonymous namespace
208
209// WallTimeImp doesn't work when CPU Scaling is enabled. If CPU Scaling is
210// enabled at the start of the program then std::chrono::system_clock is used
211// instead.
212WallTime Now()
213{
214  static bool useCPUClock = UseCpuCycleClock();
215  if (useCPUClock) {
216    return CPUWalltimeNow();
217  } else {
218    return ChronoWalltimeNow();
219  }
220}
221
222}  // end namespace walltime
223
224
225namespace {
226
227std::string DateTimeString(bool local) {
228  typedef std::chrono::system_clock Clock;
229  std::time_t now = Clock::to_time_t(Clock::now());
230  char storage[128];
231  std::size_t written;
232
233  if (local) {
234#if defined(BENCHMARK_OS_WINDOWS)
235    written = std::strftime(storage, sizeof(storage), "%x %X", ::localtime(&now));
236#else
237    std::tm timeinfo;
238    std::memset(&timeinfo, 0, sizeof(std::tm));
239    ::localtime_r(&now, &timeinfo);
240    written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo);
241#endif
242  } else {
243#if defined(BENCHMARK_OS_WINDOWS)
244    written = std::strftime(storage, sizeof(storage), "%x %X", ::gmtime(&now));
245#else
246    std::tm timeinfo;
247    std::memset(&timeinfo, 0, sizeof(std::tm));
248    ::gmtime_r(&now, &timeinfo);
249    written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo);
250#endif
251  }
252  CHECK(written < arraysize(storage));
253  ((void)written); // prevent unused variable in optimized mode.
254  return std::string(storage);
255}
256
257} // end namespace
258
259std::string LocalDateTimeString() {
260  return DateTimeString(true);
261}
262
263}  // end namespace benchmark
trunk/3rdparty/benchmark/src/walltime.h
r0r253077
1#ifndef BENCHMARK_WALLTIME_H_
2#define BENCHMARK_WALLTIME_H_
3
4#include <string>
5
6namespace benchmark {
7typedef double WallTime;
8
9namespace walltime {
10WallTime Now();
11}  // end namespace walltime
12
13std::string LocalDateTimeString();
14
15}  // end namespace benchmark
16
17#endif  // BENCHMARK_WALLTIME_H_
trunk/3rdparty/benchmark/test/CMakeLists.txt
r0r253077
1# Enable the tests
2
3find_package(Threads REQUIRED)
4
5set(CXX03_FLAGS "${CMAKE_CXX_FLAGS}")
6string(REPLACE "-std=c++11" "-std=c++03" CXX03_FLAGS "${CXX03_FLAGS}")
7string(REPLACE "-std=c++0x" "-std=c++03" CXX03_FLAGS "${CXX03_FLAGS}")
8
9macro(compile_benchmark_test name)
10  add_executable(${name} "${name}.cc")
11  target_link_libraries(${name} benchmark ${CMAKE_THREAD_LIBS_INIT})
12endmacro(compile_benchmark_test)
13
14# Demonstration executable
15compile_benchmark_test(benchmark_test)
16add_test(benchmark benchmark_test --benchmark_min_time=0.01)
17
18compile_benchmark_test(filter_test)
19macro(add_filter_test name filter expect)
20  add_test(${name} filter_test --benchmark_min_time=0.01 --benchmark_filter=${filter} ${expect})
21endmacro(add_filter_test)
22
23add_filter_test(filter_simple "Foo" 3)
24add_filter_test(filter_suffix "BM_.*" 4)
25add_filter_test(filter_regex_all ".*" 5)
26add_filter_test(filter_regex_blank "" 5)
27add_filter_test(filter_regex_none "monkey" 0)
28add_filter_test(filter_regex_wildcard ".*Foo.*" 3)
29add_filter_test(filter_regex_begin "^BM_.*" 4)
30add_filter_test(filter_regex_begin2 "^N" 1)
31add_filter_test(filter_regex_end ".*Ba$" 1)
32
33compile_benchmark_test(options_test)
34add_test(options_benchmarks options_test --benchmark_min_time=0.01)
35
36compile_benchmark_test(basic_test)
37add_test(basic_benchmark basic_test --benchmark_min_time=0.01)
38
39compile_benchmark_test(fixture_test)
40add_test(fixture_test fixture_test --benchmark_min_time=0.01)
41
42compile_benchmark_test(cxx03_test)
43set_target_properties(cxx03_test
44    PROPERTIES COMPILE_FLAGS "${CXX03_FLAGS}")
45add_test(cxx03 cxx03_test --benchmark_min_time=0.01)
46
47# Add the coverage command(s)
48if(CMAKE_BUILD_TYPE)
49  string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER)
50endif()
51if (${CMAKE_BUILD_TYPE_LOWER} MATCHES "coverage")
52  find_program(GCOV gcov)
53  find_program(LCOV lcov)
54  find_program(GENHTML genhtml)
55  find_program(CTEST ctest)
56  if (GCOV AND LCOV AND GENHTML AND CTEST AND HAVE_CXX_FLAG_COVERAGE)
57    add_custom_command(
58      OUTPUT ${CMAKE_BINARY_DIR}/lcov/index.html
59      COMMAND ${LCOV} -q -z -d .
60      COMMAND ${LCOV} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o before.lcov -i
61      COMMAND ${CTEST} --force-new-ctest-process
62      COMMAND ${LCOV} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o after.lcov
63      COMMAND ${LCOV} -q -a before.lcov -a after.lcov --output-file final.lcov
64      COMMAND ${LCOV} -q -r final.lcov "'${CMAKE_SOURCE_DIR}/test/*'" -o final.lcov
65      COMMAND ${GENHTML} final.lcov -o lcov --demangle-cpp --sort -p "${CMAKE_BINARY_DIR}" -t benchmark
66      DEPENDS filter_test benchmark_test options_test basic_test fixture_test cxx03_test
67      WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
68      COMMENT "Running LCOV"
69    )
70    add_custom_target(coverage
71      DEPENDS ${CMAKE_BINARY_DIR}/lcov/index.html
72      COMMENT "LCOV report at lcov/index.html"
73    )
74    message(STATUS "Coverage command added")
75  else()
76    if (HAVE_CXX_FLAG_COVERAGE)
77      set(CXX_FLAG_COVERAGE_MESSAGE supported)
78    else()
79      set(CXX_FLAG_COVERAGE_MESSAGE unavailable)
80    endif()
81    message(WARNING
82      "Coverage not available:\n"
83      "  gcov: ${GCOV}\n"
84      "  lcov: ${LCOV}\n"
85      "  genhtml: ${GENHTML}\n"
86      "  ctest: ${CTEST}\n"
87      "  --coverage flag: ${CXX_FLAG_COVERAGE_MESSAGE}")
88  endif()
89endif()
trunk/3rdparty/benchmark/test/basic_test.cc
r0r253077
1
2#include "benchmark/benchmark_api.h"
3
4#define BASIC_BENCHMARK_TEST(x) \
5    BENCHMARK(x)->Arg(8)->Arg(512)->Arg(8192)
6
7void BM_empty(benchmark::State& state) {
8  while (state.KeepRunning()) {
9    benchmark::DoNotOptimize(state.iterations());
10  }
11}
12BENCHMARK(BM_empty);
13BENCHMARK(BM_empty)->ThreadPerCpu();
14
15void BM_spin_empty(benchmark::State& state) {
16  while (state.KeepRunning()) {
17    for (int x = 0; x < state.range_x(); ++x) {
18      benchmark::DoNotOptimize(x);
19    }
20  }
21}
22BASIC_BENCHMARK_TEST(BM_spin_empty);
23BASIC_BENCHMARK_TEST(BM_spin_empty)->ThreadPerCpu();
24
25void BM_spin_pause_before(benchmark::State& state) {
26  for (int i = 0; i < state.range_x(); ++i) {
27    benchmark::DoNotOptimize(i);
28  }
29  while(state.KeepRunning()) {
30    for (int i = 0; i < state.range_x(); ++i) {
31      benchmark::DoNotOptimize(i);
32    }
33  }
34}
35BASIC_BENCHMARK_TEST(BM_spin_pause_before);
36BASIC_BENCHMARK_TEST(BM_spin_pause_before)->ThreadPerCpu();
37
38
39void BM_spin_pause_during(benchmark::State& state) {
40  while(state.KeepRunning()) {
41    state.PauseTiming();
42    for (int i = 0; i < state.range_x(); ++i) {
43      benchmark::DoNotOptimize(i);
44    }
45    state.ResumeTiming();
46    for (int i = 0; i < state.range_x(); ++i) {
47      benchmark::DoNotOptimize(i);
48    }
49  }
50}
51BASIC_BENCHMARK_TEST(BM_spin_pause_during);
52BASIC_BENCHMARK_TEST(BM_spin_pause_during)->ThreadPerCpu();
53
54void BM_pause_during(benchmark::State& state) {
55  while(state.KeepRunning()) {
56    state.PauseTiming();
57    state.ResumeTiming();
58  }
59}
60BENCHMARK(BM_pause_during);
61BENCHMARK(BM_pause_during)->ThreadPerCpu();
62BENCHMARK(BM_pause_during)->UseRealTime();
63BENCHMARK(BM_pause_during)->UseRealTime()->ThreadPerCpu();
64
65void BM_spin_pause_after(benchmark::State& state) {
66  while(state.KeepRunning()) {
67    for (int i = 0; i < state.range_x(); ++i) {
68      benchmark::DoNotOptimize(i);
69    }
70  }
71  for (int i = 0; i < state.range_x(); ++i) {
72    benchmark::DoNotOptimize(i);
73  }
74}
75BASIC_BENCHMARK_TEST(BM_spin_pause_after);
76BASIC_BENCHMARK_TEST(BM_spin_pause_after)->ThreadPerCpu();
77
78
79void BM_spin_pause_before_and_after(benchmark::State& state) {
80  for (int i = 0; i < state.range_x(); ++i) {
81    benchmark::DoNotOptimize(i);
82  }
83  while(state.KeepRunning()) {
84    for (int i = 0; i < state.range_x(); ++i) {
85      benchmark::DoNotOptimize(i);
86    }
87  }
88  for (int i = 0; i < state.range_x(); ++i) {
89    benchmark::DoNotOptimize(i);
90  }
91}
92BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after);
93BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after)->ThreadPerCpu();
94
95
96void BM_empty_stop_start(benchmark::State& state) {
97  while (state.KeepRunning()) { }
98}
99BENCHMARK(BM_empty_stop_start);
100BENCHMARK(BM_empty_stop_start)->ThreadPerCpu();
101
102BENCHMARK_MAIN()
trunk/3rdparty/benchmark/test/benchmark_test.cc
r0r253077
1#include "benchmark/benchmark.h"
2
3#include <assert.h>
4#include <math.h>
5#include <stdint.h>
6
7#include <cstdlib>
8#include <iostream>
9#include <limits>
10#include <list>
11#include <map>
12#include <mutex>
13#include <set>
14#include <sstream>
15#include <string>
16#include <vector>
17
18#if defined(__GNUC__)
19# define BENCHMARK_NOINLINE __attribute__((noinline))
20#else
21# define BENCHMARK_NOINLINE
22#endif
23
24namespace {
25
26int BENCHMARK_NOINLINE Factorial(uint32_t n) {
27  return (n == 1) ? 1 : n * Factorial(n - 1);
28}
29
30double CalculatePi(int depth) {
31  double pi = 0.0;
32  for (int i = 0; i < depth; ++i) {
33    double numerator = static_cast<double>(((i % 2) * 2) - 1);
34    double denominator = static_cast<double>((2 * i) - 1);
35    pi += numerator / denominator;
36  }
37  return (pi - 1.0) * 4;
38}
39
40std::set<int> ConstructRandomSet(int size) {
41  std::set<int> s;
42  for (int i = 0; i < size; ++i)
43    s.insert(i);
44  return s;
45}
46
47std::mutex test_vector_mu;
48std::vector<int>* test_vector = nullptr;
49
50}  // end namespace
51
52static void BM_Factorial(benchmark::State& state) {
53  int fac_42 = 0;
54  while (state.KeepRunning())
55    fac_42 = Factorial(8);
56  // Prevent compiler optimizations
57  std::stringstream ss;
58  ss << fac_42;
59  state.SetLabel(ss.str());
60}
61BENCHMARK(BM_Factorial);
62BENCHMARK(BM_Factorial)->UseRealTime();
63
64static void BM_CalculatePiRange(benchmark::State& state) {
65  double pi = 0.0;
66  while (state.KeepRunning())
67    pi = CalculatePi(state.range_x());
68  std::stringstream ss;
69  ss << pi;
70  state.SetLabel(ss.str());
71}
72BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024);
73
74static void BM_CalculatePi(benchmark::State& state) {
75  static const int depth = 1024;
76  while (state.KeepRunning()) {
77    benchmark::DoNotOptimize(CalculatePi(depth));
78  }
79}
80BENCHMARK(BM_CalculatePi)->Threads(8);
81BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32);
82BENCHMARK(BM_CalculatePi)->ThreadPerCpu();
83
84static void BM_SetInsert(benchmark::State& state) {
85  while (state.KeepRunning()) {
86    state.PauseTiming();
87    std::set<int> data = ConstructRandomSet(state.range_x());
88    state.ResumeTiming();
89    for (int j = 0; j < state.range_y(); ++j)
90      data.insert(rand());
91  }
92  state.SetItemsProcessed(state.iterations() * state.range_y());
93  state.SetBytesProcessed(state.iterations() * state.range_y() * sizeof(int));
94}
95BENCHMARK(BM_SetInsert)->RangePair(1<<10,8<<10, 1,10);
96
97template<typename Container, typename ValueType = typename Container::value_type>
98static void BM_Sequential(benchmark::State& state) {
99  ValueType v = 42;
100  while (state.KeepRunning()) {
101    Container c;
102    for (int i = state.range_x(); --i; )
103      c.push_back(v);
104  }
105  const size_t items_processed = state.iterations() * state.range_x();
106  state.SetItemsProcessed(items_processed);
107  state.SetBytesProcessed(items_processed * sizeof(v));
108}
109BENCHMARK_TEMPLATE2(BM_Sequential, std::vector<int>, int)->Range(1 << 0, 1 << 10);
110BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10);
111// Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond.
112#if __cplusplus >= 201103L
113BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>, int)->Arg(512);
114#endif
115
116static void BM_StringCompare(benchmark::State& state) {
117  std::string s1(state.range_x(), '-');
118  std::string s2(state.range_x(), '-');
119  while (state.KeepRunning())
120    benchmark::DoNotOptimize(s1.compare(s2));
121}
122BENCHMARK(BM_StringCompare)->Range(1, 1<<20);
123
124static void BM_SetupTeardown(benchmark::State& state) {
125  if (state.thread_index == 0) {
126    // No need to lock test_vector_mu here as this is running single-threaded.
127    test_vector = new std::vector<int>();
128  }
129  int i = 0;
130  while (state.KeepRunning()) {
131    std::lock_guard<std::mutex> l(test_vector_mu);
132    if (i%2 == 0)
133      test_vector->push_back(i);
134    else
135      test_vector->pop_back();
136    ++i;
137  }
138  if (state.thread_index == 0) {
139    delete test_vector;
140  }
141}
142BENCHMARK(BM_SetupTeardown)->ThreadPerCpu();
143
144static void BM_LongTest(benchmark::State& state) {
145  double tracker = 0.0;
146  while (state.KeepRunning()) {
147    for (int i = 0; i < state.range_x(); ++i)
148      benchmark::DoNotOptimize(tracker += i);
149  }
150}
151BENCHMARK(BM_LongTest)->Range(1<<16,1<<28);
152
153BENCHMARK_MAIN()
154
trunk/3rdparty/benchmark/test/cxx03_test.cc
r0r253077
1
2#include <cstddef>
3
4#include "benchmark/benchmark.h"
5
6#if __cplusplus >= 201103L
7#error C++11 or greater detected. Should be C++03.
8#endif
9
10void BM_empty(benchmark::State& state) {
11    while (state.KeepRunning()) {
12        volatile std::size_t x = state.iterations();
13        ((void)x);
14    }
15}
16BENCHMARK(BM_empty);
17
18template <class T, class U>
19void BM_template2(benchmark::State& state) {
20    BM_empty(state);
21}
22BENCHMARK_TEMPLATE2(BM_template2, int, long);
23
24template <class T>
25void BM_template1(benchmark::State& state) {
26    BM_empty(state);
27}
28BENCHMARK_TEMPLATE(BM_template1, long);
29BENCHMARK_TEMPLATE1(BM_template1, int);
30
31BENCHMARK_MAIN()
trunk/3rdparty/benchmark/test/filter_test.cc
r0r253077
1#include "benchmark/benchmark.h"
2
3#include <cassert>
4#include <cmath>
5#include <cstdint>
6#include <cstdlib>
7
8#include <iostream>
9#include <limits>
10#include <sstream>
11#include <string>
12
13namespace {
14
15class TestReporter : public benchmark::ConsoleReporter {
16 public:
17  virtual bool ReportContext(const Context& context) {
18    return ConsoleReporter::ReportContext(context);
19  };
20
21  virtual void ReportRuns(const std::vector<Run>& report) {
22    ++count_;
23    ConsoleReporter::ReportRuns(report);
24  };
25
26  TestReporter() : count_(0) {}
27
28  virtual ~TestReporter() {}
29
30  size_t GetCount() const {
31    return count_;
32  }
33
34 private:
35  mutable size_t count_;
36};
37
38}  // end namespace
39
40
41static void NoPrefix(benchmark::State& state) {
42  while (state.KeepRunning()) {}
43}
44BENCHMARK(NoPrefix);
45
46static void BM_Foo(benchmark::State& state) {
47  while (state.KeepRunning()) {}
48}
49BENCHMARK(BM_Foo);
50
51
52static void BM_Bar(benchmark::State& state) {
53  while (state.KeepRunning()) {}
54}
55BENCHMARK(BM_Bar);
56
57
58static void BM_FooBar(benchmark::State& state) {
59  while (state.KeepRunning()) {}
60}
61BENCHMARK(BM_FooBar);
62
63
64static void BM_FooBa(benchmark::State& state) {
65  while (state.KeepRunning()) {}
66}
67BENCHMARK(BM_FooBa);
68
69
70
71int main(int argc, char* argv[]) {
72  benchmark::Initialize(&argc, argv);
73
74  TestReporter test_reporter;
75  benchmark::RunSpecifiedBenchmarks(&test_reporter);
76
77  if (argc == 2) {
78    // Make sure we ran all of the tests
79    std::stringstream ss(argv[1]);
80    size_t expected;
81    ss >> expected;
82
83    const size_t count = test_reporter.GetCount();
84    if (count != expected) {
85      std::cerr << "ERROR: Expected " << expected << " tests to be ran but only "
86                << count << " completed" << std::endl;
87      return -1;
88    }
89  }
90  return 0;
91}
trunk/3rdparty/benchmark/test/fixture_test.cc
r0r253077
1
2#include "benchmark/benchmark.h"
3
4#include <cassert>
5
6class MyFixture : public ::benchmark::Fixture
7{
8public:
9    void SetUp() {
10        data = new int(42);
11    }
12
13    void TearDown() {
14        assert(data != nullptr);
15        delete data;
16        data = nullptr;
17    }
18
19    ~MyFixture() {
20      assert(data == nullptr);
21    }
22
23    int* data;
24};
25
26
27BENCHMARK_F(MyFixture, Foo)(benchmark::State& st) {
28    assert(data != nullptr);
29    assert(*data == 42);
30    while (st.KeepRunning()) {
31    }
32}
33
34BENCHMARK_DEFINE_F(MyFixture, Bar)(benchmark::State& st) {
35  while (st.KeepRunning()) {
36  }
37  st.SetItemsProcessed(st.range_x());
38}
39BENCHMARK_REGISTER_F(MyFixture, Bar)->Arg(42);
40
41
42BENCHMARK_MAIN()
trunk/3rdparty/benchmark/test/options_test.cc
r0r253077
1#include "benchmark/benchmark_api.h"
2
3void BM_basic(benchmark::State& state) {
4  while (state.KeepRunning()) {
5  }
6}
7BENCHMARK(BM_basic);
8BENCHMARK(BM_basic)->Arg(42);
9BENCHMARK(BM_basic)->Range(1, 8);
10BENCHMARK(BM_basic)->DenseRange(10, 15);
11BENCHMARK(BM_basic)->ArgPair(42, 42);
12BENCHMARK(BM_basic)->RangePair(64, 512, 64, 512);
13BENCHMARK(BM_basic)->MinTime(0.7);
14BENCHMARK(BM_basic)->UseRealTime();
15BENCHMARK(BM_basic)->ThreadRange(2, 4);
16BENCHMARK(BM_basic)->ThreadPerCpu();
17
18void CustomArgs(benchmark::internal::Benchmark* b) {
19  for (int i = 0; i < 10; ++i) {
20    b->Arg(i);
21  }
22}
23
24BENCHMARK(BM_basic)->Apply(CustomArgs);
25
26BENCHMARK_MAIN()
trunk/benchmarks/eminline_native.cpp
r0r253077
1// license:BSD-3-Clause
2// copyright-holders:Miodrag Milanovic
3
4#include "benchmark/benchmark_api.h"
5#include "osdcomm.h"
6#include "eminline.h"
7static void BM_count_leading_zeros_native(benchmark::State& state) {
8   UINT32 cnt = 0x332533;
9   while (state.KeepRunning()) {
10      (void)count_leading_zeros(cnt);
11      cnt++;
12   }
13}
14// Register the function as a benchmark
15BENCHMARK(BM_count_leading_zeros_native);
trunk/benchmarks/eminline_noasm.cpp
r0r253077
1// license:BSD-3-Clause
2// copyright-holders:Miodrag Milanovic
3
4#include "benchmark/benchmark_api.h"
5#include <time.h>
6#include "osdcore.h"
7#include "osdcomm.h"
8#define MAME_NOASM 1
9osd_ticks_t osd_ticks(void)
10{
11   // use the standard library clock function
12   return clock();
13}
14#include "eminline.h"
15
16static void BM_count_leading_zeros_noasm(benchmark::State& state) {
17   UINT32 cnt = 0x332533;
18   while (state.KeepRunning()) {
19      (void)count_leading_zeros(cnt);
20      cnt++;
21   }
22}
23// Register the function as a benchmark
24BENCHMARK(BM_count_leading_zeros_noasm);
trunk/benchmarks/main.cpp
r0r253077
1// license:BSD-3-Clause
2// copyright-holders:Miodrag Milanovic
3
4#include "benchmark/benchmark_api.h"
5
6BENCHMARK_MAIN();
No newline at end of file
trunk/makefile
r253076r253077
2020# SUBTARGET = tiny
2121# TOOLS = 1
2222# TESTS = 1
23# BENCHMARKS = 1
2324# OSD = sdl
2425
2526# USE_BGFX = 1
r253076r253077
473474PARAMS += --with-tests
474475endif
475476
477ifdef BENCHMARKS
478PARAMS += --with-benchmarks
479endif
480
476481ifdef SYMBOLS
477482PARAMS += --SYMBOLS='$(SYMBOLS)'
478483endif
r253076r253077
698703   scripts/src/sound.lua \
699704   scripts/src/tools.lua \
700705   scripts/src/tests.lua \
706   scripts/src/benchmarks.lua \
701707   scripts/src/video.lua \
702708   scripts/src/bus.lua \
703709   scripts/src/netlist.lua \
trunk/scripts/genie.lua
r253076r253077
8383}
8484
8585newoption {
86   trigger = "with-benchmarks",
87   description = "Enable building benchmarks.",
88}
89
90newoption {
8691   trigger = "osd",
8792   description = "Choose OSD layer implementation",
8893}
r253076r253077
12961301   group "tests"
12971302   dofile(path.join("src", "tests.lua"))
12981303end
1304
1305if _OPTIONS["with-benchmarks"] then
1306   group "benchmarks"
1307   dofile(path.join("src", "benchmarks.lua"))
1308end
trunk/scripts/src/3rdparty.lua
r253076r253077
917917   "portaudio",
918918}
919919end
920
921--------------------------------------------------
922-- GoogleTest library objects
923--------------------------------------------------
924
925project "gtest"
926   uuid "fa306a8d-fb10-4d4a-9d2e-fdb9076407b4"
927   kind "StaticLib"
928
929   configuration { "gmake" }
930      buildoptions {
931         "-Wno-undef",
932         "-Wno-unused-variable",
933      }
934
935   configuration { "mingw-clang" }
936      buildoptions {
937         "-O0", -- crash of compiler when doing optimization
938      }
939
940   configuration { "vs*" }
941if _OPTIONS["vs"]=="intel-15" then
942      buildoptions {
943         "/Qwd1195",          -- error #1195: conversion from integer to smaller pointer
944      }
945end
946
947   configuration { }
948
949   includedirs {
950      MAME_DIR .. "3rdparty/googletest/googletest/include",
951      MAME_DIR .. "3rdparty/googletest/googletest",
952   }
953   files {
954      MAME_DIR .. "3rdparty/googletest/googletest/src/gtest-all.cc",
955   }
trunk/scripts/src/benchmarks.lua
r0r253077
1-- license:BSD-3-Clause
2-- copyright-holders:MAMEdev Team
3
4---------------------------------------------------------------------------
5--
6--   benchmarks.lua
7--
8--   Rules for building benchmarks
9--
10---------------------------------------------------------------------------
11
12--------------------------------------------------
13-- Google Benchmark library objects
14--------------------------------------------------
15
16project "benchmark"
17   uuid "60a7e05c-8b4f-497c-bfda-2949a009ba0d"
18   kind "StaticLib"
19
20   configuration { }
21      defines {
22         "HAVE_STD_REGEX",
23      }
24
25   includedirs {
26      MAME_DIR .. "3rdparty/benchmark/include",
27   }
28   files {
29      MAME_DIR .. "3rdparty/benchmark/src/benchmark.cc",
30      MAME_DIR .. "3rdparty/benchmark/src/colorprint.cc",
31      MAME_DIR .. "3rdparty/benchmark/src/commandlineflags.cc",
32      MAME_DIR .. "3rdparty/benchmark/src/console_reporter.cc",
33      MAME_DIR .. "3rdparty/benchmark/src/csv_reporter.cc",
34      MAME_DIR .. "3rdparty/benchmark/src/json_reporter.cc",
35      MAME_DIR .. "3rdparty/benchmark/src/log.cc",
36      MAME_DIR .. "3rdparty/benchmark/src/reporter.cc",
37      MAME_DIR .. "3rdparty/benchmark/src/sleep.cc",
38      MAME_DIR .. "3rdparty/benchmark/src/string_util.cc",
39      MAME_DIR .. "3rdparty/benchmark/src/sysinfo.cc",
40      MAME_DIR .. "3rdparty/benchmark/src/walltime.cc",
41      MAME_DIR .. "3rdparty/benchmark/src/re_std.cc",
42   }
43
44
45
46project("benchmarks")
47   uuid ("a9750a48-d283-4a6d-b126-31c7ce049af1")
48   kind "ConsoleApp"   
49
50   flags {
51      "Symbols", -- always include minimum symbols for executables   
52   }
53
54   if _OPTIONS["SEPARATE_BIN"]~="1" then
55      targetdir(MAME_DIR)
56   end
57
58   configuration { }
59
60   links {
61      "benchmark",
62   }
63
64   includedirs {
65      MAME_DIR .. "3rdparty/benchmark/include",
66      MAME_DIR .. "src/osd",
67   }
68
69   files {
70      MAME_DIR .. "benchmarks/main.cpp",
71      MAME_DIR .. "benchmarks/eminline_native.cpp",
72      MAME_DIR .. "benchmarks/eminline_noasm.cpp",
73   }
74
trunk/scripts/src/tests.lua
r253076r253077
88--   Rules for building tests
99--
1010---------------------------------------------------------------------------
11--------------------------------------------------
12-- GoogleTest library objects
13--------------------------------------------------
1114
12project("tests")
13uuid ("66d4c639-196b-4065-a411-7ee9266564f5")
14kind "ConsoleApp"   
15project "gtest"
16   uuid "fa306a8d-fb10-4d4a-9d2e-fdb9076407b4"
17   kind "StaticLib"
1518
16flags {
17   "Symbols", -- always include minimum symbols for executables   
18}
19   configuration { "gmake" }
20      buildoptions {
21         "-Wno-undef",
22         "-Wno-unused-variable",
23      }
1924
20if _OPTIONS["SEPARATE_BIN"]~="1" then
21   targetdir(MAME_DIR)
25   configuration { "mingw-clang" }
26      buildoptions {
27         "-O0", -- crash of compiler when doing optimization
28      }
29
30   configuration { "vs*" }
31if _OPTIONS["vs"]=="intel-15" then
32      buildoptions {
33         "/Qwd1195",          -- error #1195: conversion from integer to smaller pointer
34      }
2235end
2336
24configuration { "gmake" }
25   buildoptions {
26      "-Wno-undef",
37   configuration { }
38
39   includedirs {
40      MAME_DIR .. "3rdparty/googletest/googletest/include",
41      MAME_DIR .. "3rdparty/googletest/googletest",
2742   }
43   files {
44      MAME_DIR .. "3rdparty/googletest/googletest/src/gtest-all.cc",
45   }
2846
29configuration { }
3047
31links {
32   "gtest",
33   "utils",
34   "expat",
35   "zlib",
36   "ocore_" .. _OPTIONS["osd"],
37}
48project("tests")
49   uuid ("66d4c639-196b-4065-a411-7ee9266564f5")
50   kind "ConsoleApp"   
3851
39includedirs {
40   MAME_DIR .. "3rdparty/googletest/googletest/include",
41   MAME_DIR .. "src/osd",
42   MAME_DIR .. "src/lib/util",
43}
52   flags {
53      "Symbols", -- always include minimum symbols for executables   
54   }
4455
45files {
46   MAME_DIR .. "tests/main.cpp",
47   MAME_DIR .. "tests/lib/util/corestr.cpp",
48}
56   if _OPTIONS["SEPARATE_BIN"]~="1" then
57      targetdir(MAME_DIR)
58   end
4959
60   configuration { "gmake" }
61      buildoptions {
62         "-Wno-undef",
63      }
64
65   configuration { }
66
67   links {
68      "gtest",
69      "utils",
70      "expat",
71      "zlib",
72      "ocore_" .. _OPTIONS["osd"],
73   }
74
75   includedirs {
76      MAME_DIR .. "3rdparty/googletest/googletest/include",
77      MAME_DIR .. "src/osd",
78      MAME_DIR .. "src/lib/util",
79   }
80
81   files {
82      MAME_DIR .. "tests/main.cpp",
83      MAME_DIR .. "tests/lib/util/corestr.cpp",
84   }
85
trunk/src/devices/cpu/i86/i86.txt
r253076r253077
29298086/8088
3030---------
3131"mov cs, " causes unconditional jump!
320xd6 is salc (sbb al,al) as all other intel x86-16 and -32 cpus
3332
343380C86/80C88
3534-----------
r253076r253077
3736
383780186/80188
3938-----------
40integrated pic, timer and dmac entirely incompatible with 8259, 825[3,4] and 82[3,5]7
39integrated pic8259, pit8253, dma8253 (but not at standard pc addresses)
4140additional instructions
42#BR/bound/int 5, #UD/illegal instruction/int 6, #NM/coprocessor unavailable/int 7 support
43"mov cs, " ignored (likely causes int 6)
41"mov cs, " ?
4442shift count anded with 0x1f
4543
464480188
r253076r253077
54528080 emulation mode
5553"mov cs, " ignored
5654shift count not anded (acts like 8086)
570xd6 is xlat alias
5855
5956NEC 70116 (V30)
6057---------------
r253076r253077
7269
7370NEC V40
7471-------
75pinout, integrated peripherals 8259,54,37 clones at nonpc compatible addresses
72pinout, integrated peripherals as 80186
7673
7774NEC V50
7875-------
79pinout, integrated peripherals as v40
76pinout, integrated peripherals as 80188
8077
8178NEC V33?
8279--------
r253076r253077
9592
969380286
9794-----
9880186 with additional instructions but no peripherals
9580186 with additional instructions
999624 bit address bus,
100protected mode selector/descriptor
97protected mode
10198
1029980386 and later
103100---------------
trunk/src/emu/debug/debugcmd.cpp
r253076r253077
23812381   for (int i = 2; i < params; i++)
23822382   {
23832383      const char *pdata = param[i];
2384      size_t pdatalen = strlen(pdata) - 1;
23852384
23862385      /* check for a string */
2387      if (pdata[0] == '"' && pdata[pdatalen] == '"')
2386      if (pdata[0] == '"' && pdata[strlen(pdata) - 1] == '"')
23882387      {
2389         for (j = 1; j < pdatalen; j++)
2388         for (j = 1; j < strlen(pdata) - 1; j++)
23902389         {
23912390            data_to_find[data_count] = pdata[j];
23922391            data_size[data_count++] = 1;
trunk/src/emu/debug/textbuf.cpp
r253076r253077
8686   text_buffer *text;
8787
8888   /* allocate memory for the text buffer object */
89   text = global_alloc_nothrow(text_buffer);
89   text = (text_buffer *)global_alloc(text_buffer);
9090   if (!text)
9191      return nullptr;
9292
9393   /* allocate memory for the buffer itself */
94   text->buffer = global_alloc_array_nothrow(char, bytes);
94   text->buffer = (char *)global_alloc_array(char, bytes);
9595   if (!text->buffer)
9696   {
9797      global_free(text);
r253076r253077
9999   }
100100
101101   /* allocate memory for the lines array */
102   text->lineoffs = global_alloc_array_nothrow(INT32, lines);
102   text->lineoffs = (INT32 *)global_alloc_array(INT32, lines);
103103   if (!text->lineoffs)
104104   {
105105      global_free_array(text->buffer);
trunk/src/emu/diimage.cpp
r253076r253077
161161   zippath_parent(m_working_directory, filename);
162162   m_basename.assign(m_image_name);
163163
164   size_t loc1 = m_image_name.find_last_of('\\');
165   size_t loc2 = m_image_name.find_last_of('/');
166   size_t loc3 = m_image_name.find_last_of(':');
167   size_t loc = MAX(loc1,MAX(loc2, loc3));
168   if (loc != -1) {
164   int loc1 = m_image_name.find_last_of('\\');
165   int loc2 = m_image_name.find_last_of('/');
166   int loc3 = m_image_name.find_last_of(':');
167   int loc = MAX(loc1,MAX(loc2,loc3));
168   if (loc!=-1) {
169169      if (loc == loc3)
170170      {
171171         // temp workaround for softlists now that m_image_name contains the part name too (e.g. list:gamename:cart)
172172         m_basename = m_basename.substr(0, loc);
173         size_t tmploc = m_basename.find_last_of(':');
174         m_basename = m_basename.substr(tmploc + 1, loc - tmploc);
173         std::string tmpstr = std::string(m_basename);
174         int tmploc = tmpstr.find_last_of(':');
175         m_basename = m_basename.substr(tmploc + 1,loc-tmploc);
175176      }
176177      else
177         m_basename = m_basename.substr(loc + 1);
178         m_basename = m_basename.substr(loc + 1, m_basename.length() - loc);
178179   }
179   m_basename_noext = m_basename;
180   m_basename_noext = m_basename.assign(m_basename);
180181   m_filetype = "";
181182   loc = m_basename_noext.find_last_of('.');
182   if (loc != -1) {
183      m_basename_noext = m_basename_noext.substr(0, loc);
184      m_filetype = m_basename.substr(loc + 1);
183   if (loc!=-1) {
184      m_basename_noext = m_basename_noext.substr(0,loc);
185      m_filetype = m_basename.assign(m_basename);
186      m_filetype = m_filetype.substr(loc + 1, m_filetype.length() - loc);
185187   }
186188
187189   return IMAGE_ERROR_SUCCESS;
trunk/src/emu/luaengine.cpp
r253076r253077
10491049   osd_lock_acquire(lock);
10501050   if (msg.ready == 1) {
10511051   lua_settop(m_lua_state, 0);
1052   int status = luaL_loadbuffer(m_lua_state, msg.text.c_str(), msg.text.length(), "=stdin");
1052   int status = luaL_loadbuffer(m_lua_state, msg.text.c_str(), strlen(msg.text.c_str()), "=stdin");
10531053   if (incomplete(status)==0)  /* cannot try to add lines? */
10541054   {
10551055      if (status == LUA_OK) status = docall(0, LUA_MULTRET);
trunk/src/emu/render.cpp
r253076r253077
10551055   if (strcmp(viewname, "auto") != 0)
10561056   {
10571057      // scan for a matching view name
1058      size_t viewlen = strlen(viewname);
10591058      for (view = view_by_index(viewindex = 0); view != nullptr; view = view_by_index(++viewindex))
1060         if (core_strnicmp(view->name(), viewname, viewlen) == 0)
1059         if (core_strnicmp(view->name(), viewname, strlen(viewname)) == 0)
10611060            break;
10621061   }
10631062
trunk/src/emu/sound/wavwrite.cpp
r253076r253077
1818   UINT16 align, temp16;
1919
2020   /* allocate memory for the wav struct */
21   wav = global_alloc_nothrow(wav_file);
21   wav = (wav_file *) global_alloc(wav_file);
2222   if (!wav)
2323      return nullptr;
2424
trunk/src/emu/ui/miscmenu.cpp
r253076r253077
434434         file_enumerator path(machine().options().crosshair_path());
435435         const osd_directory_entry *dir;
436436         /* reset search flags */
437         bool using_default = false;
438         bool finished = false;
439         bool found = false;
437         int using_default = false;
438         int finished = false;
439         int found = false;
440440
441441         /* if we are using the default, then we just need to find the first in the list */
442442         if (*(settings.name) == 0)
trunk/src/emu/ui/selgame.h
r253076r253077
3131   // internal state
3232   enum { VISIBLE_GAMES_IN_LIST = 15 };
3333   UINT8                   m_error;
34   bool                    m_rerandomize;
34   UINT8                   m_rerandomize;
3535   char                    m_search[40];
3636   int                     m_matchlist[VISIBLE_GAMES_IN_LIST];
3737   std::vector<const game_driver *> m_driverlist;
trunk/src/emu/ui/ui.cpp
r253076r253077
183183    CORE IMPLEMENTATION
184184***************************************************************************/
185185
186static const UINT32 mouse_bitmap[32*32] =
187{
186static const UINT32 mouse_bitmap[] = {
188187   0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,
189188   0x09a46f30,0x81ac7c43,0x24af8049,0x00ad7d45,0x00a8753a,0x00a46f30,0x009f6725,0x009b611c,0x00985b14,0x0095560d,0x00935308,0x00915004,0x00904e02,0x008f4e01,0x008f4d00,0x008f4d00,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,
190189   0x00a16a29,0xa2aa783d,0xffbb864a,0xc0b0824c,0x5aaf7f48,0x09ac7b42,0x00a9773c,0x00a67134,0x00a26b2b,0x009e6522,0x009a5e19,0x00965911,0x0094550b,0x00925207,0x00915004,0x008f4e01,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,0x00ffffff,
r253076r253077
237236   m_handler_param = 0;
238237   m_single_step = false;
239238   m_showfps = false;
240   m_showfps_end = 0;
239   m_showfps_end = false;
241240   m_show_profiler = false;
242241   m_popup_text_end = 0;
243242   m_use_natural_keyboard = false;
r253076r253077
458457      {
459458         float mouse_y=-1,mouse_x=-1;
460459         if (mouse_target->map_point_container(mouse_target_x, mouse_target_y, *container, mouse_x, mouse_y)) {
461            container->add_quad(mouse_x,mouse_y,mouse_x + 0.02f*container->manager().ui_aspect(container),mouse_y + 0.02f,UI_TEXT_COLOR,m_mouse_arrow_texture,PRIMFLAG_ANTIALIAS(1)|PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA));
460            container->add_quad(mouse_x,mouse_y,mouse_x + 0.05f*container->manager().ui_aspect(container),mouse_y + 0.05f,UI_TEXT_COLOR,m_mouse_arrow_texture,PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA));
462461         }
463462      }
464463   }
r253076r253077
15041503   // first draw the FPS counter
15051504   if (machine.ui().show_fps_counter())
15061505   {
1506      std::string tempstring;
15071507      machine.ui().draw_text_full(container, machine.video().speed_text().c_str(), 0.0f, 0.0f, 1.0f,
15081508               JUSTIFY_RIGHT, WRAP_WORD, DRAW_OPAQUE, ARGB_WHITE, ARGB_BLACK, nullptr, nullptr);
15091509   }
trunk/src/emu/video.cpp
r253076r253077
584584//  forward
585585//-------------------------------------------------
586586
587inline bool video_manager::effective_autoframeskip() const
587inline int video_manager::effective_autoframeskip() const
588588{
589589   // if we're fast forwarding or paused, autoframeskip is disabled
590590   if (m_fastforward || machine().paused())
trunk/src/emu/video.h
r253076r253077
100100   void postload();
101101
102102   // effective value helpers
103   bool effective_autoframeskip() const;
103   int effective_autoframeskip() const;
104104   int effective_frameskip() const;
105105   bool effective_throttle() const;
106106
trunk/src/lib/util/corealloc.h
r253076r253077
2727
2828// global allocation helpers -- use these instead of new and delete
2929#define global_alloc(_type)                         new _type
30#define global_alloc_nothrow(_type)                 new (std::nothrow) _type
3130#define global_alloc_array(_type, _num)             new _type[_num]
32#define global_alloc_array_nothrow(_type, _num)     new (std::nothrow) _type[_num]
3331#define global_free(_ptr)                           do { delete _ptr; } while (0)
3432#define global_free_array(_ptr)                     do { delete[] _ptr; } while (0)
3533
trunk/src/mame/drivers/fidel6502.cpp
r253076r253077
3636      : fidelz80base_state(mconfig, type, tag),
3737      m_6821pia(*this, "6821pia"),
3838      m_cart(*this, "cartslot"),
39      m_speaker(*this, "speaker")
39      m_speaker(*this, "speaker"),
40      m_irq_off(*this, "irq_off")
4041   { }
4142
4243   // devices/pointers
4344   optional_device<pia6821_device> m_6821pia;
4445   optional_device<generic_slot_device> m_cart;
4546   optional_device<speaker_sound_device> m_speaker;
47   optional_device<timer_device> m_irq_off;
4648   
47   TIMER_DEVICE_CALLBACK_MEMBER(irq_on) { m_maincpu->set_input_line(M6502_IRQ_LINE, ASSERT_LINE); }
48   TIMER_DEVICE_CALLBACK_MEMBER(irq_off) { m_maincpu->set_input_line(M6502_IRQ_LINE, CLEAR_LINE); }
49
5049   // model CSC
5150   void csc_update_7442();
5251   void csc_prepare_display();
r253076r253077
6665   // model SC12
6766   DECLARE_MACHINE_START(sc12);
6867   DECLARE_DEVICE_IMAGE_LOAD_MEMBER(scc_cartridge);
68   TIMER_DEVICE_CALLBACK_MEMBER(irq_off);
69   TIMER_DEVICE_CALLBACK_MEMBER(sc12_irq);
6970   DECLARE_WRITE8_MEMBER(sc12_control_w);
7071   DECLARE_READ8_MEMBER(sc12_input_r);
7172};
r253076r253077
246247}
247248
248249
250// interrupt handling
251
252TIMER_DEVICE_CALLBACK_MEMBER(fidel6502_state::irq_off)
253{
254   m_maincpu->set_input_line(M6502_IRQ_LINE, CLEAR_LINE);
255}
256
257TIMER_DEVICE_CALLBACK_MEMBER(fidel6502_state::sc12_irq)
258{
259   m_maincpu->set_input_line(M6502_IRQ_LINE, ASSERT_LINE);
260   m_irq_off->adjust(attotime::from_nsec(15250)); // active low for 15.25us
261}
262
263
249264// TTL
250265
251266WRITE8_MEMBER(fidel6502_state::sc12_control_w)
r253076r253077
556571   /* basic machine hardware */
557572   MCFG_CPU_ADD("maincpu", R65C02, XTAL_4MHz)
558573   MCFG_CPU_PROGRAM_MAP(sc12_map)
559   MCFG_TIMER_DRIVER_ADD_PERIODIC("irq_on", fidel6502_state, irq_on, attotime::from_hz(780)) // from 556 timer
560   MCFG_TIMER_START_DELAY(attotime::from_hz(780) - attotime::from_nsec(15250)) // active for 15.25us
561   MCFG_TIMER_DRIVER_ADD_PERIODIC("irq_off", fidel6502_state, irq_off, attotime::from_hz(780))
574   MCFG_TIMER_DRIVER_ADD_PERIODIC("sc12_irq", fidel6502_state, sc12_irq, attotime::from_hz(780)) // from 556 timer
575   MCFG_TIMER_DRIVER_ADD("irq_off", fidel6502_state, irq_off)
562576
563577   MCFG_TIMER_DRIVER_ADD_PERIODIC("display_decay", fidelz80base_state, display_decay_tick, attotime::from_msec(1))
564578   MCFG_DEFAULT_LAYOUT(layout_fidel_sc12)
r253076r253077
581595static MACHINE_CONFIG_START( fev, fidel6502_state )
582596
583597   /* basic machine hardware */
584   MCFG_CPU_ADD("maincpu", M65SC02, XTAL_12MHz/4) // G65SC102
598   MCFG_CPU_ADD("maincpu", M65SC02, XTAL_3MHz) // M65SC102 (CMD)
585599   MCFG_CPU_PROGRAM_MAP(fev_map)
586600
587601   MCFG_TIMER_DRIVER_ADD_PERIODIC("display_decay", fidelz80base_state, display_decay_tick, attotime::from_msec(1))
r253076r253077
635649/*    YEAR  NAME      PARENT  COMPAT  MACHINE  INPUT     INIT              COMPANY, FULLNAME, FLAGS */
636650COMP( 1981, csc,     0,      0,      csc,  csc, driver_device,   0, "Fidelity Electronics", "Champion Sensory Chess Challenger", MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
637651
638COMP( 1984, fscc12,     0,      0,      sc12,  sc12, driver_device,   0, "Fidelity Electronics", "Sensory Chess Challenger 12-B", MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE )
652COMP( 1984, fscc12,     0,      0,      sc12,  sc12, driver_device,   0, "Fidelity Electronics", "Sensory Chess Challenger 12-B", MACHINE_NOT_WORKING )
639653
640COMP( 1987, fexcelv,     0,      0,      fev,  csc, driver_device,   0, "Fidelity Electronics", "Voice Excellence", MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE )
654COMP( 1987, fexcelv,     0,      0,      fev,  csc, driver_device,   0, "Fidelity Electronics", "Voice Excellence", MACHINE_NOT_WORKING )
trunk/src/mame/drivers/fidelz80.cpp
r253076r253077
598598PB.4 - white wire (and TSI BUSY line)
599599PB.5 - selection jumper input (see below)
600600PB.6 - TSI start line
601PB.7 - TSI ROM A12 line
601PB.7 - TSI ROM D0 line
602602
603603
604604selection jumpers:
r253076r253077
10701070{
10711071   // d0-d3: select digits
10721072   // d0-d7: select leds, input mux low bits
1073   m_inp_mux = (m_inp_mux & ~0xff) | data;
1073   m_inp_mux = (m_inp_mux & 0x300) | data;
10741074   m_led_select = data;
10751075   vsc_prepare_display();
10761076}
r253076r253077
10811081READ8_MEMBER(fidelz80_state::vsc_pio_porta_r)
10821082{
10831083   // d0-d7: multiplexed inputs
1084   return read_inputs(11);
1085   
1084   return read_inputs(10);
10861085}
10871086
10881087READ8_MEMBER(fidelz80_state::vsc_pio_portb_r)
r253076r253077
10911090
10921091   // d4: TSI BUSY line
10931092   ret |= (m_speech->busy_r()) ? 0 : 0x10;
1094   
1093
10951094   return ret;
10961095}
10971096
10981097WRITE8_MEMBER(fidelz80_state::vsc_pio_portb_w)
10991098{
11001099   // d0,d1: input mux highest bits
1101   // d5: enable language switch
1102   m_inp_mux = (m_inp_mux & ~0x700) | (data << 8 & 0x300) | (data << 5 & 0x400);
1103   
1104   //if (m_inp_mux & 0x400) debugger_break(machine());
1105   
1106   // d7: TSI ROM A12
1107   
1108   m_speech->force_update(); // update stream to now
1109   m_speech_bank = data >> 7 & 1;
1110   
1100   m_inp_mux = (m_inp_mux & 0xff) | (data << 8 & 0x300);
1101
11111102   // d6: TSI START line
11121103   m_speech->start_w(data >> 6 & 1);
1113   
1104
11141105   // d2: lower TSI volume
11151106   m_speech->set_output_gain(0, (data & 4) ? 0.5 : 1.0);
11161107}
r253076r253077
13071298   PORT_START("IN.4")
13081299   PORT_BIT(0x0f, IP_ACTIVE_HIGH, IPT_UNUSED)
13091300
1310   PORT_START("LEVEL") // hardwired (VCC/GND?)
1311   PORT_CONFNAME( 0x80, 0x00, "Maximum Levels" )
1312   PORT_CONFSETTING( 0x00, "10" ) // factory setting
1301   PORT_START("LEVEL") // factory setting
1302   PORT_CONFNAME( 0x80, 0x00, "PPI.B.7: Maximum Levels" )
1303   PORT_CONFSETTING( 0x00, "10" )
13131304   PORT_CONFSETTING( 0x80, "3" )
13141305INPUT_PORTS_END
13151306
13161307static INPUT_PORTS_START( vcc )
13171308   PORT_INCLUDE( vcc_base )
13181309
1319   PORT_START("IN.4") // PCB jumpers, not consumer accessible
1320   PORT_CONFNAME( 0x01, 0x00, "Language: French" )
1310   PORT_START("IN.4") // not consumer accessible
1311   PORT_CONFNAME( 0x01, 0x00, "PCB Jumper: French" )
13211312   PORT_CONFSETTING(    0x00, DEF_STR( Off ) )
13221313   PORT_CONFSETTING(    0x01, DEF_STR( On ) )
1323   PORT_CONFNAME( 0x02, 0x00, "Language: Spanish" )
1314   PORT_CONFNAME( 0x02, 0x00, "PCB Jumper: Spanish" )
13241315   PORT_CONFSETTING(    0x00, DEF_STR( Off ) )
13251316   PORT_CONFSETTING(    0x02, DEF_STR( On ) )
1326   PORT_CONFNAME( 0x04, 0x00, "Language: German" )
1317   PORT_CONFNAME( 0x04, 0x00, "PCB Jumper: German" )
13271318   PORT_CONFSETTING(    0x00, DEF_STR( Off ) )
13281319   PORT_CONFSETTING(    0x04, DEF_STR( On ) )
1329   PORT_CONFNAME( 0x08, 0x00, "Language: Special" )
1320   PORT_CONFNAME( 0x08, 0x00, "PCB Jumper: Special" )
13301321   PORT_CONFSETTING(    0x00, DEF_STR( Off ) )
13311322   PORT_CONFSETTING(    0x08, DEF_STR( On ) )
13321323INPUT_PORTS_END
r253076r253077
13351326   PORT_INCLUDE( vcc )
13361327
13371328   PORT_MODIFY("IN.4")
1338   PORT_CONFNAME( 0x01, 0x01, "Language: French" )
1329   PORT_CONFNAME( 0x01, 0x01, "PCB Jumper: French" )
13391330   PORT_CONFSETTING(    0x00, DEF_STR( Off ) )
13401331   PORT_CONFSETTING(    0x01, DEF_STR( On ) )
13411332INPUT_PORTS_END
r253076r253077
13441335   PORT_INCLUDE( vcc )
13451336
13461337   PORT_MODIFY("IN.4")
1347   PORT_CONFNAME( 0x02, 0x02, "Language: Spanish" )
1338   PORT_CONFNAME( 0x02, 0x02, "PCB Jumper: Spanish" )
13481339   PORT_CONFSETTING(    0x00, DEF_STR( Off ) )
13491340   PORT_CONFSETTING(    0x02, DEF_STR( On ) )
13501341INPUT_PORTS_END
r253076r253077
13531344   PORT_INCLUDE( vcc )
13541345
13551346   PORT_MODIFY("IN.4")
1356   PORT_CONFNAME( 0x04, 0x04, "Language: German" )
1347   PORT_CONFNAME( 0x04, 0x04, "PCB Jumper: German" )
13571348   PORT_CONFSETTING(    0x00, DEF_STR( Off ) )
13581349   PORT_CONFSETTING(    0x04, DEF_STR( On ) )
13591350INPUT_PORTS_END
r253076r253077
14581449   PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("DM") PORT_CODE(KEYCODE_M)
14591450   PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("ST") PORT_CODE(KEYCODE_S)
14601451   PORT_BIT(0xc0, IP_ACTIVE_HIGH, IPT_UNUSED)
1461
1462   PORT_START("IN.10") // hardwired (2 diodes)
1463   PORT_CONFNAME( 0x03, 0x00, "Language" )
1464   PORT_CONFSETTING( 0x00, "English" )
1465   PORT_CONFSETTING( 0x01, "1" ) // todo: game dasm says it checks against 0/not0, 2, 3.. which language is which?
1466   PORT_CONFSETTING( 0x02, "2" )
1467   PORT_CONFSETTING( 0x03, "3" )
14681452INPUT_PORTS_END
14691453
14701454static INPUT_PORTS_START( vbrc )
r253076r253077
15981582   /* sound hardware */
15991583   MCFG_SPEAKER_STANDARD_MONO("mono")
16001584   MCFG_SOUND_ADD("speech", S14001A, 25000) // R/C circuit, around 25khz
1601   MCFG_S14001A_EXT_READ_HANDLER(READ8(fidelz80_state, vcc_speech_r))
16021585   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.75)
16031586MACHINE_CONFIG_END
16041587
r253076r253077
17221705   ROM_LOAD("101-64109.bin", 0x2000, 0x2000, CRC(08a3577c) SHA1(69fe379d21a9d4b57c84c3832d7b3e7431eec341) )
17231706   ROM_LOAD("101-32024.bin", 0x4000, 0x1000, CRC(2a078676) SHA1(db2f0aba7e8ac0f84a17bae7155210cdf0813afb) )
17241707
1725   ROM_REGION( 0x2000, "speech", 0 )
1708   ROM_REGION( 0x1000, "speech", 0 )
17261709   ROM_LOAD("101-32107.bin", 0x0000, 0x1000, CRC(f35784f9) SHA1(348e54a7fa1e8091f89ac656b4da22f28ca2e44d) )
1727   ROM_RELOAD(               0x1000, 0x1000)
17281710ROM_END
17291711
1730ROM_START( vscsp )
1731   ROM_REGION( 0x10000, "maincpu", 0 )
1732   ROM_LOAD("101-64108.bin", 0x0000, 0x2000, CRC(c9c98490) SHA1(e6db883df088d60463e75db51433a4b01a3e7626) )
1733   ROM_LOAD("101-64109.bin", 0x2000, 0x2000, CRC(08a3577c) SHA1(69fe379d21a9d4b57c84c3832d7b3e7431eec341) )
1734   ROM_LOAD("101-32024.bin", 0x4000, 0x1000, CRC(2a078676) SHA1(db2f0aba7e8ac0f84a17bae7155210cdf0813afb) )
17351712
1736   ROM_REGION( 0x2000, "speech", 0 )
1737   ROM_LOAD("vcc-spanish.bin", 0x0000, 0x2000, BAD_DUMP CRC(8766e128) SHA1(78c7413bf240159720b131ab70bfbdf4e86eb1e9) ) // taken from vcc/fexcelv, assume correct
1738ROM_END
1739
1740ROM_START( vscg )
1741   ROM_REGION( 0x10000, "maincpu", 0 )
1742   ROM_LOAD("101-64108.bin", 0x0000, 0x2000, CRC(c9c98490) SHA1(e6db883df088d60463e75db51433a4b01a3e7626) )
1743   ROM_LOAD("101-64109.bin", 0x2000, 0x2000, CRC(08a3577c) SHA1(69fe379d21a9d4b57c84c3832d7b3e7431eec341) )
1744   ROM_LOAD("101-32024.bin", 0x4000, 0x1000, CRC(2a078676) SHA1(db2f0aba7e8ac0f84a17bae7155210cdf0813afb) )
1745
1746   ROM_REGION( 0x2000, "speech", 0 )
1747   ROM_LOAD("vcc-german.bin", 0x0000, 0x2000, BAD_DUMP CRC(6c85e310) SHA1(20d1d6543c1e6a1f04184a2df2a468f33faec3ff) ) // taken from fexcelv, assume correct
1748ROM_END
1749
1750ROM_START( vscfr )
1751   ROM_REGION( 0x10000, "maincpu", 0 )
1752   ROM_LOAD("101-64108.bin", 0x0000, 0x2000, CRC(c9c98490) SHA1(e6db883df088d60463e75db51433a4b01a3e7626) )
1753   ROM_LOAD("101-64109.bin", 0x2000, 0x2000, CRC(08a3577c) SHA1(69fe379d21a9d4b57c84c3832d7b3e7431eec341) )
1754   ROM_LOAD("101-32024.bin", 0x4000, 0x1000, CRC(2a078676) SHA1(db2f0aba7e8ac0f84a17bae7155210cdf0813afb) )
1755
1756   ROM_REGION( 0x2000, "speech", 0 )
1757   ROM_LOAD("vcc-french.bin", 0x0000, 0x2000, BAD_DUMP CRC(fe8c5c18) SHA1(2b64279ab3747ee81c86963c13e78321c6cfa3a3) ) // taken from fexcelv, assume correct
1758ROM_END
1759
1760
17611713ROM_START( vbrc ) // AKA model 7002
17621714   ROM_REGION( 0x10000, "maincpu", 0 )
17631715   // nec 2364 mask roms; pin 27 (PGM, probably NC here due to mask roms) goes to the pcb
r253076r253077
18051757COMP( 1980, uvcg,     vcc,    0,      vcc,     vccg,   driver_device, 0, "Fidelity Electronics", "Advanced Voice Chess Challenger (German)", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING )
18061758COMP( 1980, uvcfr,    vcc,    0,      vcc,     vccfr,  driver_device, 0, "Fidelity Electronics", "Advanced Voice Chess Challenger (French)", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING )
18071759
1808COMP( 1980, vsc,      0,      0,      vsc,     vsc,    driver_device, 0, "Fidelity Electronics", "Voice Sensory Chess Challenger (English)", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING | MACHINE_CLICKABLE_ARTWORK )
1809COMP( 1980, vscsp,    vsc,    0,      vsc,     vsc,    driver_device, 0, "Fidelity Electronics", "Voice Sensory Chess Challenger (Spanish)", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING | MACHINE_CLICKABLE_ARTWORK )
1810COMP( 1980, vscg,     vsc,    0,      vsc,     vsc,    driver_device, 0, "Fidelity Electronics", "Voice Sensory Chess Challenger (German)", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING | MACHINE_CLICKABLE_ARTWORK )
1811COMP( 1980, vscfr,    vsc,    0,      vsc,     vsc,    driver_device, 0, "Fidelity Electronics", "Voice Sensory Chess Challenger (French)", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING | MACHINE_CLICKABLE_ARTWORK )
1760COMP( 1980, vsc,      0,      0,      vsc,     vsc,    driver_device, 0, "Fidelity Electronics", "Voice Sensory Chess Challenger", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING | MACHINE_CLICKABLE_ARTWORK )
18121761
18131762COMP( 1979, vbrc,     0,      0,      vbrc,    vbrc,   driver_device, 0, "Fidelity Electronics", "Voice Bridge Challenger", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING )
18141763COMP( 1980, bridgec3, vbrc,   0,      vbrc,    vbrc,   driver_device, 0, "Fidelity Electronics", "Voice Bridge Challenger III", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING )
trunk/src/mame/drivers/hh_cop400.cpp
r253076r253077
824824CONS( 1979, funrlgl,   0,        0, funrlgl,   funrlgl,   driver_device, 0, "Mattel", "Funtronics Red Light Green Light", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING )
825825
826826CONS( 1980, plus1,     0,        0, plus1,     plus1,     driver_device, 0, "Milton Bradley", "Plus One", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING )
827CONS( 1981, lightfgt,  0,        0, lightfgt,  lightfgt,  driver_device, 0, "Milton Bradley", "Lightfight", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
827CONS( 1981, lightfgt,  0,        0, lightfgt,  lightfgt,  driver_device, 0, "Milton Bradley", "Lightfight", MACHINE_SUPPORTS_SAVE )
trunk/src/mame/drivers/hh_tms1k.cpp
r253076r253077
49094909CONS( 1980, mdndclab,  0,        0, mdndclab,  mdndclab,  driver_device, 0, "Mattel", "Dungeons & Dragons - Computer Labyrinth Game", MACHINE_SUPPORTS_SAVE ) // ***
49104910
49114911CONS( 1977, comp4,     0,        0, comp4,     comp4,     driver_device, 0, "Milton Bradley", "Comp IV", MACHINE_SUPPORTS_SAVE | MACHINE_NO_SOUND_HW )
4912CONS( 1978, simon,     0,        0, simon,     simon,     driver_device, 0, "Milton Bradley", "Simon (Rev. A)", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
4913CONS( 1979, ssimon,    0,        0, ssimon,    ssimon,    driver_device, 0, "Milton Bradley", "Super Simon", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
4912CONS( 1978, simon,     0,        0, simon,     simon,     driver_device, 0, "Milton Bradley", "Simon (Rev. A)", MACHINE_SUPPORTS_SAVE )
4913CONS( 1979, ssimon,    0,        0, ssimon,    ssimon,    driver_device, 0, "Milton Bradley", "Super Simon", MACHINE_SUPPORTS_SAVE )
49144914CONS( 1979, bigtrak,   0,        0, bigtrak,   bigtrak,   driver_device, 0, "Milton Bradley", "Big Trak", MACHINE_SUPPORTS_SAVE | MACHINE_MECHANICAL ) // ***
49154915
49164916CONS( 1977, cnsector,  0,        0, cnsector,  cnsector,  driver_device, 0, "Parker Brothers", "Code Name: Sector", MACHINE_SUPPORTS_SAVE | MACHINE_NO_SOUND_HW ) // ***
4917CONS( 1978, merlin,    0,        0, merlin,    merlin,    driver_device, 0, "Parker Brothers", "Merlin - The Electronic Wizard", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
4917CONS( 1978, merlin,    0,        0, merlin,    merlin,    driver_device, 0, "Parker Brothers", "Merlin - The Electronic Wizard", MACHINE_SUPPORTS_SAVE )
49184918CONS( 1979, stopthie,  0,        0, stopthief, stopthief, driver_device, 0, "Parker Brothers", "Stop Thief (Electronic Crime Scanner)", MACHINE_SUPPORTS_SAVE ) // ***
49194919CONS( 1979, stopthiep, stopthie, 0, stopthief, stopthief, driver_device, 0, "Parker Brothers", "Stop Thief (Electronic Crime Scanner) (patent)", MACHINE_SUPPORTS_SAVE | MACHINE_NOT_WORKING )
49204920CONS( 1980, bankshot,  0,        0, bankshot,  bankshot,  driver_device, 0, "Parker Brothers", "Bank Shot - Electronic Pool", MACHINE_SUPPORTS_SAVE )
49214921CONS( 1980, splitsec,  0,        0, splitsec,  splitsec,  driver_device, 0, "Parker Brothers", "Split Second", MACHINE_SUPPORTS_SAVE )
4922CONS( 1982, mmerlin,   0,        0, mmerlin,   mmerlin,   driver_device, 0, "Parker Brothers", "Master Merlin", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
4922CONS( 1982, mmerlin,   0,        0, mmerlin,   mmerlin,   driver_device, 0, "Parker Brothers", "Master Merlin", MACHINE_SUPPORTS_SAVE )
49234923
4924CONS( 1981, tandy12,   0,        0, tandy12,   tandy12,   driver_device, 0, "Tandy Radio Shack", "Tandy-12: Computerized Arcade", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK ) // some of the minigames: ***
4924CONS( 1981, tandy12,   0,        0, tandy12,   tandy12,   driver_device, 0, "Tandy Radio Shack", "Tandy-12: Computerized Arcade", MACHINE_SUPPORTS_SAVE ) // some of the minigames: ***
49254925
49264926CONS( 1979, tbreakup,  0,        0, tbreakup,  tbreakup,  driver_device, 0, "Tomy", "Break Up (Tomy)", MACHINE_SUPPORTS_SAVE )
49274927CONS( 1980, phpball,   0,        0, phpball,   phpball,   driver_device, 0, "Tomy", "Power House Pinball", MACHINE_SUPPORTS_SAVE | MACHINE_REQUIRES_ARTWORK )
trunk/src/mame/drivers/iteagle.cpp
r253076r253077
179179
180180static MACHINE_CONFIG_DERIVED( gtfore01, iteagle )
181181   MCFG_DEVICE_MODIFY(PCI_ID_FPGA)
182   MCFG_ITEAGLE_FPGA_INIT(0x00000401, 0x0b0b0b)
182   MCFG_ITEAGLE_FPGA_INIT(0x01000401, 0x0b0b0b)
183183   MCFG_DEVICE_MODIFY(PCI_ID_EEPROM)
184184   MCFG_ITEAGLE_EEPROM_INIT(0x0401, 0x7)
185185MACHINE_CONFIG_END
r253076r253077
187187static MACHINE_CONFIG_DERIVED( gtfore02, iteagle )
188188   MCFG_DEVICE_MODIFY(PCI_ID_FPGA)
189189   MCFG_ITEAGLE_FPGA_INIT(0x01000402, 0x020201)
190   MCFG_DEVICE_MODIFY(PCI_ID_EEPROM)
190   MCFG_DEVICE_MODIFY(":pci:0a.0")
191191   MCFG_ITEAGLE_EEPROM_INIT(0x0402, 0x7)
192192MACHINE_CONFIG_END
193193
r253076r253077
215215static MACHINE_CONFIG_DERIVED( gtfore06, iteagle )
216216   MCFG_DEVICE_MODIFY(PCI_ID_FPGA)
217217   MCFG_ITEAGLE_FPGA_INIT(0x01000406, 0x0c0b0d)
218   MCFG_DEVICE_MODIFY(PCI_ID_EEPROM)
218   MCFG_DEVICE_MODIFY(":pci:0a.0")
219219   MCFG_ITEAGLE_EEPROM_INIT(0x0406, 0x9);
220220MACHINE_CONFIG_END
221221
222222static MACHINE_CONFIG_DERIVED( carnking, iteagle )
223223   MCFG_DEVICE_MODIFY(PCI_ID_FPGA)
224   MCFG_ITEAGLE_FPGA_INIT(0x01000a01, 0x0e0a0a)
224   MCFG_ITEAGLE_FPGA_INIT(0x01000603, 0x0c0b0d)
225225   MCFG_DEVICE_MODIFY(PCI_ID_EEPROM)
226   MCFG_ITEAGLE_EEPROM_INIT(0x0a01, 0x9)
226   MCFG_ITEAGLE_EEPROM_INIT(0x0603, 0x9)
227227MACHINE_CONFIG_END
228228
229229static MACHINE_CONFIG_DERIVED( bbhsc, iteagle )
230230   MCFG_DEVICE_MODIFY(PCI_ID_FPGA)
231   MCFG_ITEAGLE_FPGA_INIT(0x02000600, 0x0c0a0a)
231   MCFG_ITEAGLE_FPGA_INIT(0x01000600, 0x0c0a0a)
232232   MCFG_DEVICE_MODIFY(PCI_ID_EEPROM)
233   MCFG_ITEAGLE_EEPROM_INIT(0x0000, 0x7)
233   MCFG_ITEAGLE_EEPROM_INIT(0x0600, 0x9)
234234MACHINE_CONFIG_END
235235
236236static MACHINE_CONFIG_DERIVED( bbhcotw, iteagle )
237237   MCFG_DEVICE_MODIFY(PCI_ID_FPGA)
238238   MCFG_ITEAGLE_FPGA_INIT(0x02000603, 0x080704)
239   MCFG_DEVICE_MODIFY(PCI_ID_EEPROM)
239   MCFG_DEVICE_MODIFY(":pci:0a.0")
240240   MCFG_ITEAGLE_EEPROM_INIT(0x0603, 0x9)
241241MACHINE_CONFIG_END
242242
r253076r253077
331331
332332INPUT_PORTS_END
333333
334static INPUT_PORTS_START( bbh )
334static INPUT_PORTS_START( bbhcotw )
335335   PORT_INCLUDE( iteagle )
336336
337337   PORT_MODIFY("IN1")
r253076r253077
557557
558558GAME( 2000, iteagle,          0,  iteagle,  iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Eagle BIOS", MACHINE_IS_BIOS_ROOT )
559559GAME( 1998, virtpool,   iteagle,  virtpool, virtpool, driver_device, 0, ROT0, "Incredible Technologies", "Virtual Pool", MACHINE_NOT_WORKING ) // random lockups on loading screens
560GAME( 2002, carnking,   iteagle,  carnking, bbh,  driver_device, 0, ROT0, "Incredible Technologies", "Carnival King (v1.00.11)", 0 )
560GAME( 2002, carnking,   iteagle,  carnking, iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Carnival King (v1.00.11)", MACHINE_NOT_WORKING )
561561GAME( 2000, gtfore01,   iteagle,  gtfore01, iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Golden Tee Fore! (v1.00.25)", 0 )
562562GAME( 2001, gtfore02,   iteagle,  gtfore02, iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Golden Tee Fore! 2002 (v2.01.06)", 0 )
563563GAME( 2002, gtfore03,   iteagle,  gtfore03, iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Golden Tee Fore! 2003 (v3.00.10)", 0 )
r253076r253077
569569GAME( 2004, gtfore05b,  gtfore05, gtfore05, iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Golden Tee Fore! 2005 Extra (v5.01.00)", 0 )
570570GAME( 2004, gtfore05c,  gtfore05, gtfore05, iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Golden Tee Fore! 2005 Extra (v5.00.00)", 0 )
571571GAME( 2005, gtfore06,   iteagle,  gtfore06, iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Golden Tee Fore! 2006 Complete (v6.00.01)", 0 )
572GAME( 2002, bbhsc,      iteagle,  bbhsc,    bbh,  driver_device, 0, ROT0, "Incredible Technologies", "Big Buck Hunter - Shooter's Challenge (v1.50.07)", MACHINE_NOT_WORKING ) // doesn't boot
573GAME( 2006, bbhcotw,    iteagle,  bbhcotw,  bbh,  driver_device, 0, ROT0, "Incredible Technologies", "Big Buck Hunter Call of the Wild (v3.02.5)", MACHINE_NOT_WORKING ) // random lockups
572GAME( 2002, bbhsc,      iteagle,  bbhsc,    iteagle,  driver_device, 0, ROT0, "Incredible Technologies", "Big Buck Hunter - Shooter's Challenge (v1.50.07)", MACHINE_NOT_WORKING ) // doesn't boot
573GAME( 2006, bbhcotw,    iteagle,  bbhcotw,  bbhcotw,  driver_device, 0, ROT0, "Incredible Technologies", "Big Buck Hunter Call of the Wild (v3.02.5)", MACHINE_NOT_WORKING ) // random lockups
trunk/src/mame/drivers/mmodular.cpp
r253076r253077
1515 Vancouver 68020 12Mhz
1616 Genius 68030 V4.00 33.333 Mhz
1717 Genius 68030 V4.01 33.333 Mhz
18 Genius 68030 V4.01 33.333x2 Mhz (custom MESS overclocked version for higher ELO)
1819 Berlin Pro 68020 24.576 Mhz (not modular board, but otherwise close to milano)
1920 Berlin Pro (London) 68020 24.576 Mhz (not modular board, but otherwise close to milano)
2021 London 68030 V5.00k 33.333 Mhz (probably the Genius 3/4 update ROM)
r253076r253077
997998MACHINE_START_MEMBER(polgar_state,van32)
998999{
9991000// patch LCD delay loop on the 68030 machines until waitstates and/or opcode timings are fixed in MAME core
1000// patches gen32 gen32_41 lond030
1001// patches gen32 gen32_41 gen32_oc lond030
10011002
10021003   UINT8 *rom = memregion("maincpu")->base();
10031004
10041005   if(rom[0x870] == 0x0c && rom[0x871] == 0x78) {
1005      rom[0x870] = 0x38;
1006      if (!strcmp(machine().system().name,"gen32_oc")) {
1007         rom[0x870] = 0x6c;
1008      } else {
1009         rom[0x870] = 0x38;
1010      }
10061011   }
10071012}
10081013
r253076r253077
16891694
16901695MACHINE_CONFIG_END
16911696
1697static MACHINE_CONFIG_DERIVED( gen32_oc, gen32 )
1698   MCFG_CPU_MODIFY("maincpu")
1699   MCFG_CPU_CLOCK( XTAL_33_333MHz * 2 )
1700   MCFG_DEVICE_REMOVE("int_timer")
1701   MCFG_TIMER_DRIVER_ADD_PERIODIC("int_timer", polgar_state, timer_update_irq6, attotime::from_hz(500))
1702
1703
1704MACHINE_CONFIG_END
1705
16921706static MACHINE_CONFIG_START( bpl32, polgar_state )
16931707   MCFG_CPU_ADD("maincpu", M68020, XTAL_24_576MHz)
16941708   MCFG_CPU_PROGRAM_MAP(bpl32_mem)
r253076r253077
18371851   ROM_LOAD("gen32_41.bin", 0x00000, 0x40000,CRC(ea9938c0) SHA1(645cf0b5b831b48104ad6cec8d78c63dbb6a588c))
18381852ROM_END
18391853
1854ROM_START( gen32_oc )
1855   ROM_REGION32_BE( 0x40000, "maincpu", 0 )
1856   ROM_LOAD("gen32_41.bin", 0x00000, 0x40000,CRC(ea9938c0) SHA1(645cf0b5b831b48104ad6cec8d78c63dbb6a588c))
1857ROM_END
1858
18401859ROM_START( berlinp )
18411860   ROM_REGION32_BE( 0x40000, "maincpu", 0 )
18421861   ROM_LOAD("berlinp.bin", 0x00000, 0x40000,CRC(82FBAF6E) SHA1(729B7CEF3DFAECC4594A6178FC4BA6015AFA6202))
r253076r253077
18851904   CONS(  1992, risc,     0,       0,      risc,      van16, driver_device,    0,       "Saitek",                    "RISC2500", MACHINE_SUPPORTS_SAVE|MACHINE_REQUIRES_ARTWORK|MACHINE_NOT_WORKING | MACHINE_CLICKABLE_ARTWORK )
18861905   CONS(  1993, gen32,    van16,   0,      gen32,     gen32, driver_device,    0,       "Hegener & Glaser Muenchen", "Mephisto Genius030 V4.00", MACHINE_SUPPORTS_SAVE|MACHINE_REQUIRES_ARTWORK | MACHINE_CLICKABLE_ARTWORK )
18871906   CONS(  1993, gen32_41, van16,   0,      gen32,     gen32, driver_device,    0,       "Hegener & Glaser Muenchen", "Mephisto Genius030 V4.01", MACHINE_SUPPORTS_SAVE|MACHINE_REQUIRES_ARTWORK | MACHINE_CLICKABLE_ARTWORK )
1907   CONS(  1993, gen32_oc, van16,   0,      gen32_oc,  gen32, driver_device,    0,       "Hegener & Glaser Muenchen", "Mephisto Genius030 V4.01OC", MACHINE_SUPPORTS_SAVE|MACHINE_REQUIRES_ARTWORK|MACHINE_UNOFFICIAL | MACHINE_CLICKABLE_ARTWORK )
18881908   CONS(  1994, berlinp,  van16,   0,      bpl32,     bpl32, driver_device,    0,       "Hegener & Glaser Muenchen", "Mephisto Berlin Pro 68020", MACHINE_SUPPORTS_SAVE|MACHINE_REQUIRES_ARTWORK | MACHINE_CLICKABLE_ARTWORK )
18891909   CONS(  1996, bpl32,    van16,   0,      bpl32,     bpl32, driver_device,    0,       "Hegener & Glaser Muenchen", "Mephisto Berlin Pro London Upgrade V5.00", MACHINE_SUPPORTS_SAVE|MACHINE_REQUIRES_ARTWORK | MACHINE_CLICKABLE_ARTWORK )
18901910   CONS(  1996, lond020,  van16,   0,      van32,     van32, driver_device,    0,       "Hegener & Glaser Muenchen", "Mephisto London 68020 32 Bit", MACHINE_SUPPORTS_SAVE|MACHINE_REQUIRES_ARTWORK | MACHINE_CLICKABLE_ARTWORK )
trunk/src/mame/drivers/overdriv.cpp
r253076r253077
7070
7171TIMER_DEVICE_CALLBACK_MEMBER(overdriv_state::overdriv_cpuA_scanline)
7272{
73   const int timer_threshold = 168; // fwiw matches 0 on mask ROM check, so IF it's a timer irq then should be close ...
7473   int scanline = param;
75   
76   m_fake_timer ++;
77   
78   // TODO: irqs routines are TOO slow right now, it ends up firing spurious irqs for whatever reason (shared ram fighting?)
79   //       this is a temporary solution to get rid of deprecat lib and the crashes, but also makes the game timer to be too slow.
80    //       Update: gameplay is actually too fast compared to timer, first attract mode shouldn't even surpass first blue car on right.
81   if(scanline == 256) // vblank-out irq
82   {
83      // m_screen->frame_number() & 1
74
75   /* TODO: irqs routines are TOO slow right now, it ends up firing spurious irqs for whatever reason (shared ram fighting?) */
76   /*       this is a temporary solution to get rid of deprecat lib and the crashes, but also makes the game timer to be too slow */
77   if(scanline == 256 && m_screen->frame_number() & 1) // vblank-out irq
8478      m_maincpu->set_input_line(4, HOLD_LINE);
85      m_subcpu->set_input_line(4, HOLD_LINE); // likely wrong
86   }
87   else if(m_fake_timer >= timer_threshold) // timer irq
88   {
89      m_fake_timer -= timer_threshold;
79   else if((scanline % 128) == 0) // timer irq
9080      m_maincpu->set_input_line(5, HOLD_LINE);
91   }
9281}
9382
9483INTERRUPT_GEN_MEMBER(overdriv_state::cpuB_interrupt)
9584{
9685   // this doesn't get turned on until the irq has happened? wrong irq?
97   if (m_k053246->k053246_is_irq_enabled())
98      m_subcpu->set_input_line(6, HOLD_LINE); // likely wrong
86//  if (m_k053246->k053246_is_irq_enabled())
87   m_subcpu->set_input_line(4, HOLD_LINE); // likely wrong
9988}
10089
10190
r253076r253077
138127
139128WRITE16_MEMBER(overdriv_state::overdriv_soundirq_w)
140129{
141   m_audiocpu->set_input_line(M6809_IRQ_LINE, ASSERT_LINE);
130   m_audiocpu->set_input_line(M6809_IRQ_LINE, HOLD_LINE);
142131}
143132
144
145133WRITE16_MEMBER(overdriv_state::overdriv_cpuB_irq_x_w)
146134{
147135   m_subcpu->set_input_line(5, HOLD_LINE); // likely wrong
r253076r253077
149137
150138WRITE16_MEMBER(overdriv_state::overdriv_cpuB_irq_y_w)
151139{
140   m_subcpu->set_input_line(6, HOLD_LINE); // likely wrong
152141}
153142
154143static ADDRESS_MAP_START( overdriv_master_map, AS_PROGRAM, 16, overdriv_state )
r253076r253077
178167   AM_RANGE(0x238000, 0x238001) AM_WRITE(overdriv_cpuB_irq_x_w)
179168ADDRESS_MAP_END
180169
181#ifdef UNUSED_FUNCTION
170// HACK ALERT
182171WRITE16_MEMBER( overdriv_state::overdriv_k053246_word_w )
183172{
184173   m_k053246->k053246_word_w(space,offset,data,mem_mask);
r253076r253077
201190   //printf("%02x %04x %04x\n", offset, data, mem_mask);
202191
203192}
204#endif
205193
206194static ADDRESS_MAP_START( overdriv_slave_map, AS_PROGRAM, 16, overdriv_state )
207195   AM_RANGE(0x000000, 0x03ffff) AM_ROM
r253076r253077
209197   AM_RANGE(0x0c0000, 0x0c1fff) AM_RAM //AM_DEVREADWRITE("k053250_1", k053250_device, ram_r, ram_w)
210198   AM_RANGE(0x100000, 0x10000f) AM_DEVREADWRITE("k053250_1", k053250_device, reg_r, reg_w)
211199   AM_RANGE(0x108000, 0x10800f) AM_DEVREADWRITE("k053250_2", k053250_device, reg_r, reg_w)
212   AM_RANGE(0x118000, 0x118fff) AM_DEVREADWRITE("k053246", k053247_device, k053247_word_r, k053247_word_w) // data gets copied to sprite chip with DMA..
200   AM_RANGE(0x118000, 0x118fff) AM_RAM AM_SHARE("sprram") //AM_DEVREADWRITE("k053246", k053247_device, k053247_word_r, k053247_word_w) // data gets copied to sprite chip with DMA..
213201   AM_RANGE(0x120000, 0x120001) AM_DEVREAD("k053246", k053247_device, k053246_word_r)
214202   AM_RANGE(0x128000, 0x128001) AM_READWRITE(cpuB_ctrl_r, cpuB_ctrl_w) /* enable K053247 ROM reading, plus something else */
215   AM_RANGE(0x130000, 0x130007) AM_DEVREADWRITE8("k053246", k053247_device, k053246_r,k053246_w,0xffff)
216   //AM_RANGE(0x140000, 0x140001) used in later stages
203   AM_RANGE(0x130000, 0x130007) AM_WRITE(overdriv_k053246_word_w) // AM_DEVWRITE("k053246", k053247_device, k053246_word_w)
217204   AM_RANGE(0x200000, 0x203fff) AM_RAM AM_SHARE("share1")
218205   AM_RANGE(0x208000, 0x20bfff) AM_RAM
219206   AM_RANGE(0x218000, 0x219fff) AM_DEVREAD("k053250_1", k053250_device, rom_r)
220207   AM_RANGE(0x220000, 0x221fff) AM_DEVREAD("k053250_2", k053250_device, rom_r)
221208ADDRESS_MAP_END
222209
223WRITE8_MEMBER(overdriv_state::sound_ack_w)
224{
225   m_audiocpu->set_input_line(M6809_IRQ_LINE, CLEAR_LINE);
226}
227
228210static ADDRESS_MAP_START( overdriv_sound_map, AS_PROGRAM, 8, overdriv_state )
229   AM_RANGE(0x0000, 0x0000) AM_WRITE(sound_ack_w)
230   // 0x012 read during explosions
231   // 0x180
232211   AM_RANGE(0x0200, 0x0201) AM_DEVREADWRITE("ymsnd", ym2151_device,read,write)
233212   AM_RANGE(0x0400, 0x042f) AM_DEVREADWRITE("k053260_1", k053260_device, read, write)
234213   AM_RANGE(0x0600, 0x062f) AM_DEVREADWRITE("k053260_2", k053260_device, read, write)
r253076r253077
243222
244223static INPUT_PORTS_START( overdriv )
245224   PORT_START("INPUTS")
246   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_TOGGLE
225   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_TOGGLE
247226   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 )
248227   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON2 )
249228   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
r253076r253077
318297
319298   /* video hardware */
320299   MCFG_SCREEN_ADD("screen", RASTER)
321   MCFG_SCREEN_RAW_PARAMS(XTAL_24MHz/4,384,0,305,264,0,224)
300   MCFG_SCREEN_REFRESH_RATE(59)
301   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500))
302   MCFG_SCREEN_SIZE(64*8, 40*8)
303   MCFG_SCREEN_VISIBLE_AREA(13*8, (64-13)*8-1, 0*8, 32*8-1 )
322304   MCFG_SCREEN_UPDATE_DRIVER(overdriv_state, screen_update_overdriv)
323305   MCFG_SCREEN_PALETTE("palette")
324306
r253076r253077
493475   ROM_LOAD( "789e02.f1", 0x100000, 0x100000, CRC(bdd3b5c6) SHA1(412332d64052c0a3714f4002c944b0e7d32980a4) )
494476ROM_END
495477
496GAMEL( 1990, overdriv,         0, overdriv, overdriv, driver_device, 0, ROT90, "Konami", "Over Drive (set 1)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE, layout_overdriv ) // US version
497GAMEL( 1990, overdriva, overdriv, overdriv, overdriv, driver_device, 0, ROT90, "Konami", "Over Drive (set 2)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE, layout_overdriv ) // Overseas?
498GAMEL( 1990, overdrivb, overdriv, overdriv, overdriv, driver_device, 0, ROT90, "Konami", "Over Drive (set 3)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE, layout_overdriv ) // Overseas?
478GAMEL( 1990, overdriv,         0, overdriv, overdriv, driver_device, 0, ROT90, "Konami", "Over Drive (set 1)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE, layout_overdriv )
479GAMEL( 1990, overdriva, overdriv, overdriv, overdriv, driver_device, 0, ROT90, "Konami", "Over Drive (set 2)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE, layout_overdriv )
480GAMEL( 1990, overdrivb, overdriv, overdriv, overdriv, driver_device, 0, ROT90, "Konami", "Over Drive (set 3)", MACHINE_IMPERFECT_GRAPHICS | MACHINE_NOT_WORKING | MACHINE_SUPPORTS_SAVE, layout_overdriv )
trunk/src/mame/drivers/pulsar.cpp
r253076r253077
254254/* ROM definition */
255255ROM_START( pulsarlb )
256256   ROM_REGION( 0x10800, "maincpu", ROMREGION_ERASEFF )
257   ROM_SYSTEM_BIOS(0, "mon7", "MP7A")
258   ROMX_LOAD( "mp7a.bin", 0x10000, 0x800, CRC(726b8a19) SHA1(43b2af84d5622c1f67584c501b730acf002a6113), ROM_BIOS(1))
259   ROM_SYSTEM_BIOS(1, "mon6", "LBOOT6") // Blank screen until floppy boots
260   ROMX_LOAD( "lboot6.rom", 0x10000, 0x800, CRC(3bca9096) SHA1(ff99288e51a9e832785ce8e3ab5a9452b1064231), ROM_BIOS(2))
257   ROM_LOAD( "mp7a.bin", 0x10000, 0x800, CRC(726b8a19) SHA1(43b2af84d5622c1f67584c501b730acf002a6113) )
261258ROM_END
262259
263260/* Driver */
trunk/src/mame/drivers/tispeak.cpp
r253076r253077
15581558
15591559COMP( 1979, lantutor,   0,        0, lantutor,     lantutor,   tispeak_state, lantutor, "Texas Instruments", "Language Tutor (patent)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_NOT_WORKING )
15601560
1561COMP( 1981, tntell,     0,        0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Touch & Tell (US, 1981 version)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_CLICKABLE_ARTWORK | MACHINE_REQUIRES_ARTWORK ) // assume there is an older version too, with CD8010 MCU
1562COMP( 1980, tntellp,    tntell,   0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Touch & Tell (patent)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_CLICKABLE_ARTWORK | MACHINE_REQUIRES_ARTWORK | MACHINE_NOT_WORKING )
1563COMP( 1981, tntelluk,   tntell,   0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Touch & Tell (UK)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_CLICKABLE_ARTWORK | MACHINE_REQUIRES_ARTWORK )
1564COMP( 1981, tntellfr,   tntell,   0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Le Livre Magique (France)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_CLICKABLE_ARTWORK | MACHINE_REQUIRES_ARTWORK )
1561COMP( 1981, tntell,     0,        0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Touch & Tell (US, 1981 version)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_REQUIRES_ARTWORK ) // assume there is an older version too, with CD8010 MCU
1562COMP( 1980, tntellp,    tntell,   0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Touch & Tell (patent)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_REQUIRES_ARTWORK | MACHINE_NOT_WORKING )
1563COMP( 1981, tntelluk,   tntell,   0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Touch & Tell (UK)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_REQUIRES_ARTWORK )
1564COMP( 1981, tntellfr,   tntell,   0, tntell,       tntell,     tispeak_state, tntell,   "Texas Instruments", "Le Livre Magique (France)", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_REQUIRES_ARTWORK )
15651565
15661566COMP( 1982, vocaid,     0,        0, vocaid,       tntell,     driver_device, 0,        "Texas Instruments", "Vocaid", MACHINE_SUPPORTS_SAVE | MACHINE_IMPERFECT_SOUND | MACHINE_REQUIRES_ARTWORK )
trunk/src/mame/includes/fidelz80.h
r253076r253077
2525
2626   // devices/pointers
2727   required_device<cpu_device> m_maincpu;
28   optional_ioport_array<11> m_inp_matrix; // max 11
28   optional_ioport_array<10> m_inp_matrix; // max 10
2929   optional_device<s14001a_device> m_speech;
3030   optional_region_ptr<UINT8> m_speech_rom;
3131
trunk/src/mame/includes/overdriv.h
r253076r253077
2424      m_k053246(*this, "k053246"),
2525      m_k053251(*this, "k053251"),
2626      m_k053252(*this, "k053252"),
27      m_sprram(*this, "sprram"),
2728      m_screen(*this, "screen")
2829   { }
2930
r253076r253077
4445   required_device<k053247_device> m_k053246;
4546   required_device<k053251_device> m_k053251;
4647   required_device<k053252_device> m_k053252;
48   required_shared_ptr<UINT16> m_sprram;
4749   required_device<screen_device> m_screen;
4850   DECLARE_WRITE16_MEMBER(eeprom_w);
4951   DECLARE_WRITE16_MEMBER(cpuA_ctrl_w);
5052   DECLARE_READ16_MEMBER(cpuB_ctrl_r);
5153   DECLARE_WRITE16_MEMBER(cpuB_ctrl_w);
5254   DECLARE_WRITE16_MEMBER(overdriv_soundirq_w);
53   DECLARE_WRITE8_MEMBER(sound_ack_w);
5455   DECLARE_WRITE16_MEMBER(overdriv_cpuB_irq_x_w);
5556   DECLARE_WRITE16_MEMBER(overdriv_cpuB_irq_y_w);
5657   virtual void machine_start() override;
r253076r253077
5859   UINT32 screen_update_overdriv(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
5960   INTERRUPT_GEN_MEMBER(cpuB_interrupt);
6061   TIMER_DEVICE_CALLBACK_MEMBER(overdriv_cpuA_scanline);
61   int m_fake_timer;
62   
62
63   DECLARE_WRITE16_MEMBER( overdriv_k053246_word_w );
6364   K051316_CB_MEMBER(zoom_callback_1);
6465   K051316_CB_MEMBER(zoom_callback_2);
6566   K053246_CB_MEMBER(sprite_callback);
trunk/src/mame/machine/iteagle_fpga.cpp
r253076r253077
44#include "coreutil.h"
55
66#define LOG_FPGA            (0)
7#define LOG_SERIAL          (0)
87#define LOG_RTC             (0)
98#define LOG_RAM             (0)
109#define LOG_EEPROM          (0)
r253076r253077
8180   m_serial_str.clear();
8281   m_serial_idx = 0;
8382   m_serial_data = false;
84   memset(m_serial_com0, 0, sizeof(m_serial_com0));
8583   memset(m_serial_com1, 0, sizeof(m_serial_com1));
8684   memset(m_serial_com2, 0, sizeof(m_serial_com2));
8785   memset(m_serial_com3, 0, sizeof(m_serial_com3));
88   m_serial_com0[0] = 0x2c;
86   memset(m_serial_com4, 0, sizeof(m_serial_com4));
8987   m_serial_com1[0] = 0x2c;
9088   m_serial_com2[0] = 0x2c;
9189   m_serial_com3[0] = 0x2c;
90   m_serial_com4[0] = 0x2c;
9291}
9392
9493void iteagle_fpga_device::update_sequence(UINT32 data)
r253076r253077
131130      val1 = ((m_seq & 0x2)<<6) | ((m_seq & 0x4)<<4) | ((m_seq & 0x8)<<2) | ((m_seq & 0x10)<<0)
132131            | ((m_seq & 0x20)>>2) | ((m_seq & 0x40)>>4) | ((m_seq & 0x80)>>6) | ((m_seq & 0x100)>>8);
133132      m_seq = (m_seq>>8) | ((feed&0xff)<<16);
133      //m_fpga_regs[offset] = (m_fpga_regs[offset]&0xFFFFFF00) | ((val1 + m_seq_rem1)&0xFF);
134134      m_fpga_regs[offset] = (m_fpga_regs[offset]&0xFFFFFF00) | ((val1 + m_seq_rem1 + m_seq_rem2)&0xFF);
135135   } else if (data & 0x2) {
136136      val1 = ((m_seq & 0x2)<<1) | ((m_seq & 0x4)>>1) | ((m_seq & 0x8)>>3);
137137      m_seq_rem1 = ((m_seq & 0x10)) | ((m_seq & 0x20)>>2) | ((m_seq & 0x40)>>4);
138      //m_seq_rem2 = ((m_seq & 0x80)>>1) | ((m_seq & 0x100)>>3) | ((m_seq & 0x200)>>5);
138139      m_seq = (m_seq>>6) | ((feed&0x3f)<<18);
139140      m_fpga_regs[offset] = (m_fpga_regs[offset]&0xFFFFFF00) | ((val1 + m_seq_rem1 + m_seq_rem2)&0xFF);
140141   } else {
r253076r253077
196197            logerror("%s:fpga_r offset %04X = %08X & %08X\n", machine().describe_context(), offset*4, result, mem_mask);
197198         break;
198199      case 0x0c/4: // 1d = modem byte
199         result = (result & 0xFFFF0000) | ((m_serial_com1[m_serial_idx]&0xff)<<8) | (m_serial_com0[m_serial_idx]&0xff);
200         result = (result & 0xFFFF0000) | ((m_serial_com2[m_serial_idx]&0xff)<<8) | (m_serial_com1[m_serial_idx]&0xff);
200201         if (ACCESSING_BITS_0_15) {
201202            m_serial_data = false;
202203            m_serial_idx = 0;
203204         }
204         if (0 && LOG_FPGA)
205         if (LOG_FPGA)
205206            logerror("%s:fpga_r offset %04X = %08X & %08X\n", machine().describe_context(), offset*4, result, mem_mask);
206207         break;
207208      case 0x1c/4: // 1d = modem byte
208         result = (result & 0xFFFF0000) | ((m_serial_com3[m_serial_idx]&0xff)<<8) | (m_serial_com2[m_serial_idx]&0xff);
209         result = (result & 0xFFFF0000) | ((m_serial_com4[m_serial_idx]&0xff)<<8) | (m_serial_com3[m_serial_idx]&0xff);
209210         if (ACCESSING_BITS_0_15) {
210211            m_serial_data = false;
211212            m_serial_idx = 0;
r253076r253077
232233            if ((m_version & 0xff00) == 0x0200)
233234               update_sequence_eg1(data & 0xff);
234235            else
235               // ATMEL Chip access.  Returns version id's when bit 7 is set.
236               update_sequence(data & 0xff);
236            // ATMEL Chip access.  Returns version id's when bit 7 is set.
237            update_sequence(data & 0xff);
237238            if (0 && LOG_FPGA)
238239                  logerror("%s:fpga_w offset %04X = %08X & %08X\n", machine().describe_context(), offset*4, data, mem_mask);
239240         }
r253076r253077
241242         if (ACCESSING_BITS_24_31 && (data & 0x01000000)) {
242243            m_cpu->set_input_line(m_irq_num, CLEAR_LINE);
243244            // Not sure what value to use here, needed for lightgun
244            m_timer->adjust(attotime::from_hz(59));
245            m_timer->adjust(attotime::from_hz(25));
245246            if (LOG_FPGA)
246247                  logerror("%s:fpga_w offset %04X = %08X & %08X Clearing interrupt(%i)\n", machine().describe_context(), offset*4, data, mem_mask, m_irq_num);
247248         } else {
r253076r253077
268269            if (!m_serial_data) {
269270               m_serial_idx = data&0xf;
270271            } else {
271               m_serial_com0[m_serial_idx] = data&0xff;
272               m_serial_com1[m_serial_idx] = data&0xff;
272273               m_serial_idx = 0;
273274            }
274275            m_serial_data = !m_serial_data;
r253076r253077
277278            if (!m_serial_data) {
278279               m_serial_idx = (data&0x0f00)>>8;
279280            } else {
280               m_serial_com1[m_serial_idx] = (data&0xff00)>>8;
281               m_serial_com2[m_serial_idx] = (data&0xff00)>>8;
281282            }
282283            m_serial_data = !m_serial_data;
283284         }
284285         if (ACCESSING_BITS_16_23) {
285286            if (m_serial_str.size()==0)
286               m_serial_str = "com0: ";
287               m_serial_str = "com1: ";
287288            m_serial_str += (data>>16)&0xff;
288289            if (((data>>16)&0xff)==0xd) {
289               if (LOG_SERIAL) logerror("%s\n", m_serial_str.c_str());
290290               osd_printf_debug("%s\n", m_serial_str.c_str());
291291               m_serial_str.clear();
292292            }
293293         }
294294         if (ACCESSING_BITS_24_31) {
295295            if (m_serial_str.size()==0)
296               m_serial_str = "com1: ";
296               m_serial_str = "com2: ";
297297            m_serial_str += (data>>24)&0xff;
298298            if (1 || ((data>>24)&0xff)==0xd) {
299               if (LOG_SERIAL) logerror("%s\n", m_serial_str.c_str());
300299               osd_printf_debug("%s\n", m_serial_str.c_str());
301300               m_serial_str.clear();
302301            }
303302         }
304         if (0 && LOG_FPGA)
303         if (LOG_FPGA)
305304               logerror("%s:fpga_w offset %04X = %08X & %08X\n", machine().describe_context(), offset*4, data, mem_mask);
306305         break;
307306      case 0x1c/4:
r253076r253077
309308            if (!m_serial_data) {
310309               m_serial_idx = data&0xf;
311310            } else {
312               m_serial_com2[m_serial_idx] = data&0xff;
311               m_serial_com3[m_serial_idx] = data&0xff;
313312               m_serial_idx = 0;
314313            }
315314            m_serial_data = !m_serial_data;
r253076r253077
318317            if (!m_serial_data) {
319318               m_serial_idx = (data&0x0f00)>>8;
320319            } else {
321               m_serial_com3[m_serial_idx] = (data&0xff00)>>8;
320               m_serial_com4[m_serial_idx] = (data&0xff00)>>8;
322321            }
323322            m_serial_data = !m_serial_data;
324323         }
325324         if (ACCESSING_BITS_16_23) {
326325            if (m_serial_str.size()==0)
327               m_serial_str = "com2: ";
326               m_serial_str = "com3: ";
328327            m_serial_str += (data>>16)&0xff;
329328            if (1 || ((data>>16)&0xff)==0xd) {
330               if (LOG_SERIAL) logerror("%s\n", m_serial_str.c_str());
331329               osd_printf_debug("%s\n", m_serial_str.c_str());
332330               m_serial_str.clear();
333331            }
334332         }
335333         if (ACCESSING_BITS_24_31) {
336334            if (m_serial_str.size()==0)
337               m_serial_str = "com3: ";
335               m_serial_str = "com4: ";
338336            m_serial_str += (data>>24)&0xff;
339337            if (((data>>24)&0xff)==0xd) {
340               if (LOG_SERIAL) logerror("%s\n", m_serial_str.c_str());
341338               osd_printf_debug("%s\n", m_serial_str.c_str());
342339               m_serial_str.clear();
343340            }
r253076r253077
652649{
653650   pci_device::device_reset();
654651   memset(m_ctrl_regs, 0, sizeof(m_ctrl_regs));
655   m_ctrl_regs[0x10/4] =  0x00070000; // 0x6=No SIMM, 0x2, 0x1, 0x0 = SIMM .  Top 16 bits are compared to 0x3. Bit 0 might be lan chip present.
652   m_ctrl_regs[0x10/4] =  0x00000000; // 0x6=No SIMM, 0x2, 0x1, 0x0 = SIMM .  Top 16 bits are compared to 0x3.
656653   memset(m_rtc_regs, 0, sizeof(m_rtc_regs));
657654   m_rtc_regs[0xa] = 0x20; // 32.768 MHz
658655   m_rtc_regs[0xb] = 0x02; // 24-hour format
trunk/src/mame/machine/iteagle_fpga.h
r253076r253077
6363   std::string m_serial_str;
6464   UINT8 m_serial_idx;
6565   bool  m_serial_data;
66   UINT8 m_serial_com0[0x10];
6766   UINT8 m_serial_com1[0x10];
6867   UINT8 m_serial_com2[0x10];
6968   UINT8 m_serial_com3[0x10];
69   UINT8 m_serial_com4[0x10];
7070
7171   UINT32 m_version;
7272   UINT32 m_seq_init;
trunk/src/mame/mess.lst
r253076r253077
21532153bridgec3
21542154vbrc
21552155vsc
2156vscg
2157vscfr
2158vscsp
21592156csc
21602157fscc12
21612158fexcelv
r253076r253077
21902187van32    // 1991 Mephisto Vancouver 68020
21912188gen32    // 1993 Mephisto Genius030 V4.00
21922189gen32_41 // 1993 Mephisto Genius030 V4.01
2190gen32_oc // 1993 Mephisto Genius030 V4.01OC
21932191berlinp  // 1994 Mephisto Berlin Pro 68020
21942192bpl32    // 1996 Mephisto Berlin Pro London Upgrade V5.00
21952193lond020  // 1996 Mephisto London 68020 32 Bit
trunk/src/osd/sdl/sdlfile.cpp
r253076r253077
134134   {
135135      (*file)->type = SDLFILE_SOCKET;
136136      filerr = sdl_open_socket(path, openflags, file, filesize);
137      if(filerr != FILERR_NONE && (*file)->socket != -1)
138         close((*file)->socket);
139137      goto error;
140138   }
141139


Previous 199869 Revisions Next


© 1997-2024 The MAME Team