File: test_numeric_cast_vs_static_cast.cpp

package info (click to toggle)
mapnik 3.0.22%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 17,260 kB
  • sloc: cpp: 144,587; python: 1,426; sh: 785; makefile: 170; xml: 140; lisp: 13
file content (80 lines) | stat: -rw-r--r-- 2,075 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "bench_framework.hpp"
// boost
#include <boost/numeric/conversion/cast.hpp>

static double STEP_NUM = 0.0000000001;
static std::uint8_t START_NUM = 2;

class test_static : public benchmark::test_case
{
    double step_;
    std::uint8_t start_;
public:
    test_static(mapnik::parameters const& params)
     : test_case(params),
       step_(STEP_NUM),
       start_(START_NUM) {}
    bool validate() const
    {
        return true;
    }
    bool operator()() const
    {
        double value_ = 0.0;
        std::uint8_t x;
        for (std::size_t i=0;i<iterations_;++i) {
            double c = static_cast<double>(start_) * value_;
            if (c >= 256.0) c = 255.0;
            if (c < 0.0) c = 0.0;
            x = static_cast<std::uint8_t>(c);
            value_ += step_;
        }
        return static_cast<double>(x) < (static_cast<double>(start_) * value_);
    }
};

using boost::numeric::positive_overflow;
using boost::numeric::negative_overflow;

class test_numeric : public benchmark::test_case
{
    double step_;
    std::uint8_t start_;
public:
    test_numeric(mapnik::parameters const& params)
     : test_case(params),
       step_(STEP_NUM),
       start_(START_NUM) {}
    bool validate() const
    {
        return true;
    }
    bool operator()() const
    {
        double value_ = 0.0;
        std::uint8_t x;
        for (std::size_t i=0;i<iterations_;++i) {
            try {
                x = boost::numeric_cast<std::uint8_t>(start_ * value_);
            }
            catch(negative_overflow&)
            {
                x = std::numeric_limits<std::uint8_t>::min();
            }
            catch(positive_overflow&)
            {
                x = std::numeric_limits<std::uint8_t>::max();
            }
            value_ += step_;
        }
        return static_cast<double>(x) < (static_cast<double>(start_) * value_);
    }
};

int main(int argc, char** argv)
{
    return benchmark::sequencer(argc, argv)
        .run<test_static>("static_cast")
        .run<test_numeric>("numeric_cast")
        .done();
}