ts_perf.cpp 74.7 KB
Newer Older
Daniil Osokin's avatar
Daniil Osokin committed
1 2
#include "precomp.hpp"

3 4 5 6
#include <map>
#include <iostream>
#include <fstream>

7
#if defined _WIN32
8 9 10 11 12 13
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif

14
#ifdef HAVE_CUDA
15
#include "opencv2/core/cuda.hpp"
16 17
#endif

18
#ifdef __ANDROID__
Daniil Osokin's avatar
Daniil Osokin committed
19 20 21
# include <sys/time.h>
#endif

22
using namespace cvtest;
Daniil Osokin's avatar
Daniil Osokin committed
23 24 25 26 27 28
using namespace perf;

int64 TestBase::timeLimitDefault = 0;
unsigned int TestBase::iterationsLimitDefault = (unsigned int)(-1);
int64 TestBase::_timeadjustment = 0;

29 30
// Item [0] will be considered the default implementation.
static std::vector<std::string> available_impls;
Daniil Osokin's avatar
Daniil Osokin committed
31

32
static std::string  param_impl;
33

34
static enum PERF_STRATEGY strategyForce = PERF_STRATEGY_DEFAULT;
35
static enum PERF_STRATEGY strategyModule = PERF_STRATEGY_SIMPLE;
36

Daniil Osokin's avatar
Daniil Osokin committed
37 38 39 40 41 42
static double       param_max_outliers;
static double       param_max_deviation;
static unsigned int param_min_samples;
static unsigned int param_force_samples;
static double       param_time_limit;
static bool         param_write_sanity;
43
static bool         param_verify_sanity;
44 45 46
#ifdef CV_COLLECT_IMPL_DATA
static bool         param_collect_impl;
#endif
47
#ifdef ENABLE_INSTRUMENTATION
48
static int          param_instrument;
49
#endif
50 51

namespace cvtest {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
52
extern bool         test_ipp_check;
53
}
54

55
#ifdef HAVE_CUDA
56
static int          param_cuda_device;
57
#endif
58

59
#ifdef __ANDROID__
Daniil Osokin's avatar
Daniil Osokin committed
60 61 62 63 64
static int          param_affinity_mask;
static bool         log_power_checkpoints;

#include <sys/syscall.h>
#include <pthread.h>
65
#include <cerrno>
Daniil Osokin's avatar
Daniil Osokin committed
66 67 68 69 70 71 72
static void setCurrentThreadAffinityMask(int mask)
{
    pid_t pid=gettid();
    int syscallres=syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
    if (syscallres)
    {
        int err=errno;
73
        CV_UNUSED(err);
Daniil Osokin's avatar
Daniil Osokin committed
74 75 76 77 78
        LOGE("Error in the syscall setaffinity: mask=%d=0x%x err=%d=0x%x", mask, mask, err, err);
    }
}
#endif

79 80
static double perf_stability_criteria = 0.03; // 3%

81 82 83 84 85 86 87 88 89 90 91 92 93
namespace {

class PerfEnvironment: public ::testing::Environment
{
public:
    void TearDown()
    {
        cv::setNumThreads(-1);
    }
};

} // namespace

Daniil Osokin's avatar
Daniil Osokin committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
static void randu(cv::Mat& m)
{
    const int bigValue = 0x00000FFF;
    if (m.depth() < CV_32F)
    {
        int minmax[] = {0, 256};
        cv::Mat mr = cv::Mat(m.rows, (int)(m.cols * m.elemSize()), CV_8U, m.ptr(), m.step[0]);
        cv::randu(mr, cv::Mat(1, 1, CV_32S, minmax), cv::Mat(1, 1, CV_32S, minmax + 1));
    }
    else if (m.depth() == CV_32F)
    {
        //float minmax[] = {-FLT_MAX, FLT_MAX};
        float minmax[] = {-bigValue, bigValue};
        cv::Mat mr = m.reshape(1);
        cv::randu(mr, cv::Mat(1, 1, CV_32F, minmax), cv::Mat(1, 1, CV_32F, minmax + 1));
    }
    else
    {
        //double minmax[] = {-DBL_MAX, DBL_MAX};
        double minmax[] = {-bigValue, bigValue};
        cv::Mat mr = m.reshape(1);
        cv::randu(mr, cv::Mat(1, 1, CV_64F, minmax), cv::Mat(1, 1, CV_64F, minmax + 1));
    }
}

/*****************************************************************************************\
*                       inner exception class for early termination
\*****************************************************************************************/

class PerfEarlyExitException: public cv::Exception {};

/*****************************************************************************************\
*                                   ::perf::Regression
\*****************************************************************************************/

Regression& Regression::instance()
{
    static Regression single;
    return single;
}

135
Regression& Regression::add(TestBase* test, const std::string& name, cv::InputArray array, double eps, ERROR_TYPE err)
Daniil Osokin's avatar
Daniil Osokin committed
136
{
137
    if(test) test->setVerified();
Daniil Osokin's avatar
Daniil Osokin committed
138 139 140
    return instance()(name, array, eps, err);
}

141 142 143 144 145 146 147 148
Regression& Regression::addMoments(TestBase* test, const std::string& name, const cv::Moments& array, double eps, ERROR_TYPE err)
{
    int len = (int)sizeof(cv::Moments) / sizeof(double);
    cv::Mat m(1, len, CV_64F, (void*)&array);

    return Regression::add(test, name, m, eps, err);
}

149 150 151
Regression& Regression::addKeypoints(TestBase* test, const std::string& name, const std::vector<cv::KeyPoint>& array, double eps, ERROR_TYPE err)
{
    int len = (int)array.size();
152 153 154 155 156 157
    cv::Mat pt      (len, 1, CV_32FC2, len ? (void*)&array[0].pt : 0,       sizeof(cv::KeyPoint));
    cv::Mat size    (len, 1, CV_32FC1, len ? (void*)&array[0].size : 0,     sizeof(cv::KeyPoint));
    cv::Mat angle   (len, 1, CV_32FC1, len ? (void*)&array[0].angle : 0,    sizeof(cv::KeyPoint));
    cv::Mat response(len, 1, CV_32FC1, len ? (void*)&array[0].response : 0, sizeof(cv::KeyPoint));
    cv::Mat octave  (len, 1, CV_32SC1, len ? (void*)&array[0].octave : 0,   sizeof(cv::KeyPoint));
    cv::Mat class_id(len, 1, CV_32SC1, len ? (void*)&array[0].class_id : 0, sizeof(cv::KeyPoint));
158 159 160 161 162 163 164 165 166

    return Regression::add(test, name + "-pt",       pt,       eps, ERROR_ABSOLUTE)
                                (name + "-size",     size,     eps, ERROR_ABSOLUTE)
                                (name + "-angle",    angle,    eps, ERROR_ABSOLUTE)
                                (name + "-response", response, eps, err)
                                (name + "-octave",   octave,   eps, ERROR_ABSOLUTE)
                                (name + "-class_id", class_id, eps, ERROR_ABSOLUTE);
}

167 168 169
Regression& Regression::addMatches(TestBase* test, const std::string& name, const std::vector<cv::DMatch>& array, double eps, ERROR_TYPE err)
{
    int len = (int)array.size();
170 171 172 173
    cv::Mat queryIdx(len, 1, CV_32SC1, len ? (void*)&array[0].queryIdx : 0, sizeof(cv::DMatch));
    cv::Mat trainIdx(len, 1, CV_32SC1, len ? (void*)&array[0].trainIdx : 0, sizeof(cv::DMatch));
    cv::Mat imgIdx  (len, 1, CV_32SC1, len ? (void*)&array[0].imgIdx : 0,   sizeof(cv::DMatch));
    cv::Mat distance(len, 1, CV_32FC1, len ? (void*)&array[0].distance : 0, sizeof(cv::DMatch));
174 175 176 177 178 179 180

    return Regression::add(test, name + "-queryIdx", queryIdx, DBL_EPSILON, ERROR_ABSOLUTE)
                                (name + "-trainIdx", trainIdx, DBL_EPSILON, ERROR_ABSOLUTE)
                                (name + "-imgIdx",   imgIdx,   DBL_EPSILON, ERROR_ABSOLUTE)
                                (name + "-distance", distance, eps, err);
}

Daniil Osokin's avatar
Daniil Osokin committed
181 182 183 184 185 186 187 188 189
void Regression::Init(const std::string& testSuitName, const std::string& ext)
{
    instance().init(testSuitName, ext);
}

void Regression::init(const std::string& testSuitName, const std::string& ext)
{
    if (!storageInPath.empty())
    {
190
        LOGE("Subsequent initialization of Regression utility is not allowed.");
Daniil Osokin's avatar
Daniil Osokin committed
191 192 193
        return;
    }

194
#ifndef WINRT
Daniil Osokin's avatar
Daniil Osokin committed
195
    const char *data_path_dir = getenv("OPENCV_TEST_DATA_PATH");
196 197 198
#else
    const char *data_path_dir = OPENCV_TEST_DATA_PATH;
#endif
199 200 201 202

    cvtest::addDataSearchSubDirectory("");
    cvtest::addDataSearchSubDirectory(testSuitName);

Daniil Osokin's avatar
Daniil Osokin committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    const char *path_separator = "/";

    if (data_path_dir)
    {
        int len = (int)strlen(data_path_dir)-1;
        if (len < 0) len = 0;
        std::string path_base = (data_path_dir[0] == 0 ? std::string(".") : std::string(data_path_dir))
                + (data_path_dir[len] == '/' || data_path_dir[len] == '\\' ? "" : path_separator)
                + "perf"
                + path_separator;

        storageInPath = path_base + testSuitName + ext;
        storageOutPath = path_base + testSuitName;
    }
    else
    {
        storageInPath = testSuitName + ext;
        storageOutPath = testSuitName;
    }

223 224
    suiteName = testSuitName;

Daniil Osokin's avatar
Daniil Osokin committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    try
    {
        if (storageIn.open(storageInPath, cv::FileStorage::READ))
        {
            rootIn = storageIn.root();
            if (storageInPath.length() > 3 && storageInPath.substr(storageInPath.length()-3) == ".gz")
                storageOutPath += "_new";
            storageOutPath += ext;
        }
    }
    catch(cv::Exception&)
    {
        LOGE("Failed to open sanity data for reading: %s", storageInPath.c_str());
    }

    if(!storageIn.isOpened())
        storageOutPath = storageInPath;
}

Regression::Regression() : regRNG(cv::getTickCount())//this rng should be really random
{
}

Regression::~Regression()
{
    if (storageIn.isOpened())
        storageIn.release();
    if (storageOut.isOpened())
    {
        if (!currentTestNodeName.empty())
            storageOut << "}";
        storageOut.release();
    }
}

cv::FileStorage& Regression::write()
{
    if (!storageOut.isOpened() && !storageOutPath.empty())
    {
        int mode = (storageIn.isOpened() && storageInPath == storageOutPath)
                ? cv::FileStorage::APPEND : cv::FileStorage::WRITE;
        storageOut.open(storageOutPath, mode);
        if (!storageOut.isOpened())
        {
            LOGE("Could not open \"%s\" file for writing", storageOutPath.c_str());
            storageOutPath.clear();
        }
        else if (mode == cv::FileStorage::WRITE && !rootIn.empty())
        {
            //TODO: write content of rootIn node into the storageOut
        }
    }
    return storageOut;
}

std::string Regression::getCurrentTestNodeName()
{
    const ::testing::TestInfo* const test_info =
      ::testing::UnitTest::GetInstance()->current_test_info();

    if (test_info == 0)
        return "undefined";

    std::string nodename = std::string(test_info->test_case_name()) + "--" + test_info->name();
    size_t idx = nodename.find_first_of('/');
    if (idx != std::string::npos)
        nodename.erase(idx);

    const char* type_param = test_info->type_param();
    if (type_param != 0)
        (nodename += "--") += type_param;

    const char* value_param = test_info->value_param();
    if (value_param != 0)
        (nodename += "--") += value_param;

    for(size_t i = 0; i < nodename.length(); ++i)
        if (!isalnum(nodename[i]) && '_' != nodename[i])
            nodename[i] = '-';

    return nodename;
}

bool Regression::isVector(cv::InputArray a)
{
310 311
    return a.kind() == cv::_InputArray::STD_VECTOR_MAT || a.kind() == cv::_InputArray::STD_VECTOR_VECTOR ||
           a.kind() == cv::_InputArray::STD_VECTOR_UMAT;
Daniil Osokin's avatar
Daniil Osokin committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
}

double Regression::getElem(cv::Mat& m, int y, int x, int cn)
{
    switch (m.depth())
    {
    case CV_8U: return *(m.ptr<unsigned char>(y, x) + cn);
    case CV_8S: return *(m.ptr<signed char>(y, x) + cn);
    case CV_16U: return *(m.ptr<unsigned short>(y, x) + cn);
    case CV_16S: return *(m.ptr<signed short>(y, x) + cn);
    case CV_32S: return *(m.ptr<signed int>(y, x) + cn);
    case CV_32F: return *(m.ptr<float>(y, x) + cn);
    case CV_64F: return *(m.ptr<double>(y, x) + cn);
    default: return 0;
    }
}

void Regression::write(cv::Mat m)
{
331 332
    if (!m.empty() && m.dims < 2) return;

Daniil Osokin's avatar
Daniil Osokin committed
333
    double min, max;
334
    cv::minMaxIdx(m, &min, &max);
Daniil Osokin's avatar
Daniil Osokin committed
335 336
    write() << "min" << min << "max" << max;

337 338
    write() << "last" << "{" << "x" << m.size.p[1] - 1 << "y" << m.size.p[0] - 1
        << "val" << getElem(m, m.size.p[0] - 1, m.size.p[1] - 1, m.channels() - 1) << "}";
Daniil Osokin's avatar
Daniil Osokin committed
339 340

    int x, y, cn;
341 342
    x = regRNG.uniform(0, m.size.p[1]);
    y = regRNG.uniform(0, m.size.p[0]);
Daniil Osokin's avatar
Daniil Osokin committed
343 344 345 346 347
    cn = regRNG.uniform(0, m.channels());
    write() << "rng1" << "{" << "x" << x << "y" << y;
    if(cn > 0) write() << "cn" << cn;
    write() << "val" << getElem(m, y, x, cn) << "}";

348 349
    x = regRNG.uniform(0, m.size.p[1]);
    y = regRNG.uniform(0, m.size.p[0]);
Daniil Osokin's avatar
Daniil Osokin committed
350 351 352 353 354 355
    cn = regRNG.uniform(0, m.channels());
    write() << "rng2" << "{" << "x" << x << "y" << y;
    if (cn > 0) write() << "cn" << cn;
    write() << "val" << getElem(m, y, x, cn) << "}";
}

356
void Regression::verify(cv::FileNode node, cv::Mat actual, double eps, std::string argname, ERROR_TYPE err)
Daniil Osokin's avatar
Daniil Osokin committed
357
{
358 359
    if (!actual.empty() && actual.dims < 2) return;

360 361 362 363 364 365
    double expect_min = (double)node["min"];
    double expect_max = (double)node["max"];

    if (err == ERROR_RELATIVE)
        eps *= std::max(std::abs(expect_min), std::abs(expect_max));

Daniil Osokin's avatar
Daniil Osokin committed
366
    double actual_min, actual_max;
367
    cv::minMaxIdx(actual, &actual_min, &actual_max);
Daniil Osokin's avatar
Daniil Osokin committed
368

369 370 371 372
    ASSERT_NEAR(expect_min, actual_min, eps)
            << argname << " has unexpected minimal value" << std::endl;
    ASSERT_NEAR(expect_max, actual_max, eps)
            << argname << " has unexpected maximal value" << std::endl;
Daniil Osokin's avatar
Daniil Osokin committed
373 374

    cv::FileNode last = node["last"];
375
    double actual_last = getElem(actual, actual.size.p[0] - 1, actual.size.p[1] - 1, actual.channels() - 1);
376 377
    int expect_cols = (int)last["x"] + 1;
    int expect_rows = (int)last["y"] + 1;
378
    ASSERT_EQ(expect_cols, actual.size.p[1])
379
            << argname << " has unexpected number of columns" << std::endl;
380
    ASSERT_EQ(expect_rows, actual.size.p[0])
381 382 383 384 385
            << argname << " has unexpected number of rows" << std::endl;

    double expect_last = (double)last["val"];
    ASSERT_NEAR(expect_last, actual_last, eps)
            << argname << " has unexpected value of the last element" << std::endl;
Daniil Osokin's avatar
Daniil Osokin committed
386 387 388 389 390 391

    cv::FileNode rng1 = node["rng1"];
    int x1 = rng1["x"];
    int y1 = rng1["y"];
    int cn1 = rng1["cn"];

392
    double expect_rng1 = (double)rng1["val"];
393 394
    // it is safe to use x1 and y1 without checks here because we have already
    // verified that mat size is the same as recorded
395 396 397 398
    double actual_rng1 = getElem(actual, y1, x1, cn1);

    ASSERT_NEAR(expect_rng1, actual_rng1, eps)
            << argname << " has unexpected value of the ["<< x1 << ":" << y1 << ":" << cn1 <<"] element" << std::endl;
Daniil Osokin's avatar
Daniil Osokin committed
399 400 401 402 403 404

    cv::FileNode rng2 = node["rng2"];
    int x2 = rng2["x"];
    int y2 = rng2["y"];
    int cn2 = rng2["cn"];

405 406 407 408 409
    double expect_rng2 = (double)rng2["val"];
    double actual_rng2 = getElem(actual, y2, x2, cn2);

    ASSERT_NEAR(expect_rng2, actual_rng2, eps)
            << argname << " has unexpected value of the ["<< x2 << ":" << y2 << ":" << cn2 <<"] element" << std::endl;
Daniil Osokin's avatar
Daniil Osokin committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
}

void Regression::write(cv::InputArray array)
{
    write() << "kind" << array.kind();
    write() << "type" << array.type();
    if (isVector(array))
    {
        int total = (int)array.total();
        int idx = regRNG.uniform(0, total);
        write() << "len" << total;
        write() << "idx" << idx;

        cv::Mat m = array.getMat(idx);

        if (m.total() * m.channels() < 26) //5x5 or smaller
            write() << "val" << m;
        else
            write(m);
    }
    else
    {
        if (array.total() * array.channels() < 26) //5x5 or smaller
            write() << "val" << array.getMat();
        else
            write(array.getMat());
    }
}

static int countViolations(const cv::Mat& expected, const cv::Mat& actual, const cv::Mat& diff, double eps, double* max_violation = 0, double* max_allowed = 0)
{
    cv::Mat diff64f;
    diff.reshape(1).convertTo(diff64f, CV_64F);

    cv::Mat expected_abs = cv::abs(expected.reshape(1));
    cv::Mat actual_abs = cv::abs(actual.reshape(1));
    cv::Mat maximum, mask;
    cv::max(expected_abs, actual_abs, maximum);
    cv::multiply(maximum, cv::Vec<double, 1>(eps), maximum, CV_64F);
    cv::compare(diff64f, maximum, mask, cv::CMP_GT);

    int v = cv::countNonZero(mask);

    if (v > 0 && max_violation != 0 && max_allowed != 0)
    {
455
        int loc[10] = {0};
Daniil Osokin's avatar
Daniil Osokin committed
456
        cv::minMaxIdx(maximum, 0, max_allowed, 0, loc, mask);
457
        *max_violation = diff64f.at<double>(loc[0], loc[1]);
Daniil Osokin's avatar
Daniil Osokin committed
458 459 460 461 462 463 464
    }

    return v;
}

void Regression::verify(cv::FileNode node, cv::InputArray array, double eps, ERROR_TYPE err)
{
465 466 467 468
    int expected_kind = (int)node["kind"];
    int expected_type = (int)node["type"];
    ASSERT_EQ(expected_kind, array.kind()) << "  Argument \"" << node.name() << "\" has unexpected kind";
    ASSERT_EQ(expected_type, array.type()) << "  Argument \"" << node.name() << "\" has unexpected type";
Daniil Osokin's avatar
Daniil Osokin committed
469 470 471 472

    cv::FileNode valnode = node["val"];
    if (isVector(array))
    {
473 474
        int expected_length = (int)node["len"];
        ASSERT_EQ(expected_length, (int)array.total()) << "  Vector \"" << node.name() << "\" has unexpected length";
Daniil Osokin's avatar
Daniil Osokin committed
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
        int idx = node["idx"];

        cv::Mat actual = array.getMat(idx);

        if (valnode.isNone())
        {
            ASSERT_LE((size_t)26, actual.total() * (size_t)actual.channels())
                    << "  \"" << node.name() << "[" <<  idx << "]\" has unexpected number of elements";
            verify(node, actual, eps, cv::format("%s[%d]", node.name().c_str(), idx), err);
        }
        else
        {
            cv::Mat expected;
            valnode >> expected;

490 491 492 493 494 495 496 497 498
            if(expected.empty())
            {
                ASSERT_TRUE(actual.empty())
                    << "  expected empty " << node.name() << "[" <<  idx<< "]";
            }
            else
            {
                ASSERT_EQ(expected.size(), actual.size())
                        << "  " << node.name() << "[" <<  idx<< "] has unexpected size";
Daniil Osokin's avatar
Daniil Osokin committed
499

500 501
                cv::Mat diff;
                cv::absdiff(expected, actual, diff);
Daniil Osokin's avatar
Daniil Osokin committed
502

503
                if (err == ERROR_ABSOLUTE)
Daniil Osokin's avatar
Daniil Osokin committed
504
                {
505 506 507 508 509 510
                    if (!cv::checkRange(diff, true, 0, 0, eps))
                    {
                        if(expected.total() * expected.channels() < 12)
                            std::cout << " Expected: " << std::endl << expected << std::endl << " Actual:" << std::endl << actual << std::endl;

                        double max;
511
                        cv::minMaxIdx(diff.reshape(1), 0, &max);
512 513

                        FAIL() << "  Absolute difference (=" << max << ") between argument \""
514
                               << node.name() << "[" <<  idx << "]\" and expected value is greater than " << eps;
515
                    }
Daniil Osokin's avatar
Daniil Osokin committed
516
                }
517
                else if (err == ERROR_RELATIVE)
Daniil Osokin's avatar
Daniil Osokin committed
518
                {
519 520 521 522
                    double maxv, maxa;
                    int violations = countViolations(expected, actual, diff, eps, &maxv, &maxa);
                    if (violations > 0)
                    {
523 524 525
                        if(expected.total() * expected.channels() < 12)
                            std::cout << " Expected: " << std::endl << expected << std::endl << " Actual:" << std::endl << actual << std::endl;

526
                        FAIL() << "  Relative difference (" << maxv << " of " << maxa << " allowed) between argument \""
527
                               << node.name() << "[" <<  idx << "]\" and expected value is greater than " << eps << " in " << violations << " points";
528
                    }
Daniil Osokin's avatar
Daniil Osokin committed
529 530 531 532 533 534 535 536 537 538
                }
            }
        }
    }
    else
    {
        if (valnode.isNone())
        {
            ASSERT_LE((size_t)26, array.total() * (size_t)array.channels())
                    << "  Argument \"" << node.name() << "\" has unexpected number of elements";
539
            verify(node, array.getMat(), eps, "Argument \"" + node.name() + "\"", err);
Daniil Osokin's avatar
Daniil Osokin committed
540 541 542 543 544 545 546
        }
        else
        {
            cv::Mat expected;
            valnode >> expected;
            cv::Mat actual = array.getMat();

547 548 549 550 551 552 553 554 555
            if(expected.empty())
            {
                ASSERT_TRUE(actual.empty())
                    << "  expected empty " << node.name();
            }
            else
            {
                ASSERT_EQ(expected.size(), actual.size())
                        << "  Argument \"" << node.name() << "\" has unexpected size";
Daniil Osokin's avatar
Daniil Osokin committed
556

557 558
                cv::Mat diff;
                cv::absdiff(expected, actual, diff);
Daniil Osokin's avatar
Daniil Osokin committed
559

560
                if (err == ERROR_ABSOLUTE)
Daniil Osokin's avatar
Daniil Osokin committed
561
                {
562 563 564 565 566 567
                    if (!cv::checkRange(diff, true, 0, 0, eps))
                    {
                        if(expected.total() * expected.channels() < 12)
                            std::cout << " Expected: " << std::endl << expected << std::endl << " Actual:" << std::endl << actual << std::endl;

                        double max;
568
                        cv::minMaxIdx(diff.reshape(1), 0, &max);
569 570

                        FAIL() << "  Difference (=" << max << ") between argument1 \"" << node.name()
571
                               << "\" and expected value is greater than " << eps;
572
                    }
Daniil Osokin's avatar
Daniil Osokin committed
573
                }
574
                else if (err == ERROR_RELATIVE)
Daniil Osokin's avatar
Daniil Osokin committed
575
                {
576 577 578 579
                    double maxv, maxa;
                    int violations = countViolations(expected, actual, diff, eps, &maxv, &maxa);
                    if (violations > 0)
                    {
580 581 582
                        if(expected.total() * expected.channels() < 12)
                            std::cout << " Expected: " << std::endl << expected << std::endl << " Actual:" << std::endl << actual << std::endl;

583
                        FAIL() << "  Relative difference (" << maxv << " of " << maxa << " allowed) between argument \"" << node.name()
584
                               << "\" and expected value is greater than " << eps << " in " << violations << " points";
585
                    }
Daniil Osokin's avatar
Daniil Osokin committed
586 587 588 589 590 591 592 593
                }
            }
        }
    }
}

Regression& Regression::operator() (const std::string& name, cv::InputArray array, double eps, ERROR_TYPE err)
{
594 595 596
    // exit if current test is already failed
    if(::testing::UnitTest::GetInstance()->current_test_info()->result()->Failed()) return *this;

597 598 599 600 601 602
    if(!array.empty() && array.depth() == CV_USRTYPE1)
    {
        ADD_FAILURE() << "  Can not check regression for CV_USRTYPE1 data type for " << name;
        return *this;
    }

Daniil Osokin's avatar
Daniil Osokin committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    std::string nodename = getCurrentTestNodeName();

    cv::FileNode n = rootIn[nodename];
    if(n.isNone())
    {
        if(param_write_sanity)
        {
            if (nodename != currentTestNodeName)
            {
                if (!currentTestNodeName.empty())
                    write() << "}";
                currentTestNodeName = nodename;

                write() << nodename << "{";
            }
618
            // TODO: verify that name is alphanumeric, current error message is useless
Daniil Osokin's avatar
Daniil Osokin committed
619 620 621 622
            write() << name << "{";
            write(array);
            write() << "}";
        }
623 624
        else if(param_verify_sanity)
        {
625
            ADD_FAILURE() << "  No regression data for " << name << " argument, test node: " << nodename;
626
        }
Daniil Osokin's avatar
Daniil Osokin committed
627 628 629 630 631 632 633 634 635
    }
    else
    {
        cv::FileNode this_arg = n[name];
        if (!this_arg.isMap())
            ADD_FAILURE() << "  No regression data for " << name << " argument";
        else
            verify(this_arg, array, eps, err);
    }
636

Daniil Osokin's avatar
Daniil Osokin committed
637 638 639 640 641 642 643 644
    return *this;
}


/*****************************************************************************************\
*                                ::perf::performance_metrics
\*****************************************************************************************/
performance_metrics::performance_metrics()
645 646 647 648 649
{
    clear();
}

void performance_metrics::clear()
Daniil Osokin's avatar
Daniil Osokin committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
{
    bytesIn = 0;
    bytesOut = 0;
    samples = 0;
    outliers = 0;
    gmean = 0;
    gstddev = 0;
    mean = 0;
    stddev = 0;
    median = 0;
    min = 0;
    frequency = 0;
    terminationReason = TERM_UNKNOWN;
}

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
/*****************************************************************************************\
*                                   Performance validation results
\*****************************************************************************************/

static bool perf_validation_enabled = false;

static std::string perf_validation_results_directory;
static std::map<std::string, float> perf_validation_results;
static std::string perf_validation_results_outfile;

static double perf_validation_criteria = 0.03; // 3 %
static double perf_validation_time_threshold_ms = 0.1;
static int perf_validation_idle_delay_ms = 3000; // 3 sec

static void loadPerfValidationResults(const std::string& fileName)
{
    perf_validation_results.clear();
    std::ifstream infile(fileName.c_str());
    while (!infile.eof())
    {
        std::string name;
        float value = 0;
        if (!(infile >> value))
        {
            if (infile.eof())
                break; // it is OK
            std::cout << "ERROR: Can't load performance validation results from " << fileName << "!" << std::endl;
            return;
        }
        infile.ignore(1);
        if (!(std::getline(infile, name)))
        {
            std::cout << "ERROR: Can't load performance validation results from " << fileName << "!" << std::endl;
            return;
        }
        if (!name.empty() && name[name.size() - 1] == '\r') // CRLF processing on Linux
            name.resize(name.size() - 1);
        perf_validation_results[name] = value;
    }
    std::cout << "Performance validation results loaded from " << fileName << " (" << perf_validation_results.size() << " entries)" << std::endl;
}

static void savePerfValidationResult(const std::string& name, float value)
{
    perf_validation_results[name] = value;
}

static void savePerfValidationResults()
{
    if (!perf_validation_results_outfile.empty())
    {
        std::ofstream outfile((perf_validation_results_directory + perf_validation_results_outfile).c_str());
        std::map<std::string, float>::const_iterator i;
        for (i = perf_validation_results.begin(); i != perf_validation_results.end(); ++i)
        {
            outfile << i->second << ';';
            outfile << i->first << std::endl;
        }
        outfile.close();
        std::cout << "Performance validation results saved (" << perf_validation_results.size() << " entries)" << std::endl;
    }
}

class PerfValidationEnvironment : public ::testing::Environment
{
public:
    virtual ~PerfValidationEnvironment() {}
    virtual void SetUp() {}

    virtual void TearDown()
    {
        savePerfValidationResults();
    }
};

740 741 742 743 744 745 746 747 748 749 750 751 752 753
#ifdef ENABLE_INSTRUMENTATION
static void printShift(cv::instr::InstrNode *pNode, cv::instr::InstrNode* pRoot)
{
    // Print empty line for a big tree nodes
    if(pNode->m_pParent)
    {
        int parendIdx = pNode->m_pParent->findChild(pNode);
        if(parendIdx > 0 && pNode->m_pParent->m_childs[parendIdx-1]->m_childs.size())
        {
            printShift(pNode->m_pParent->m_childs[parendIdx-1]->m_childs[0], pRoot);
            printf("\n");
        }
    }

754
    // Check if parents have more childes
755 756 757 758 759 760 761 762 763 764 765
    std::vector<cv::instr::InstrNode*> cache;
    cv::instr::InstrNode *pTmpNode = pNode;
    while(pTmpNode->m_pParent && pTmpNode->m_pParent != pRoot)
    {
        cache.push_back(pTmpNode->m_pParent);
        pTmpNode = pTmpNode->m_pParent;
    }
    for(int i = (int)cache.size()-1; i >= 0; i--)
    {
        if(cache[i]->m_pParent)
        {
766
            if(cache[i]->m_pParent->findChild(cache[i]) == (int)cache[i]->m_pParent->m_childs.size()-1)
767 768 769 770 771 772 773 774 775 776
                printf("    ");
            else
                printf("|   ");
        }
    }
}

static double calcLocalWeight(cv::instr::InstrNode *pNode)
{
    if(pNode->m_pParent && pNode->m_pParent->m_pParent)
777
        return ((double)pNode->m_payload.m_ticksTotal*100/pNode->m_pParent->m_payload.m_ticksTotal);
778 779 780 781 782 783 784 785 786 787 788
    else
        return 100;
}

static double calcGlobalWeight(cv::instr::InstrNode *pNode)
{
    cv::instr::InstrNode* globNode = pNode;

    while(globNode->m_pParent && globNode->m_pParent->m_pParent)
        globNode = globNode->m_pParent;

789
    return ((double)pNode->m_payload.m_ticksTotal*100/(double)globNode->m_payload.m_ticksTotal);
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
}

static void printNodeRec(cv::instr::InstrNode *pNode, cv::instr::InstrNode *pRoot)
{
    printf("%s", (pNode->m_payload.m_funName.substr(0, 40) + ((pNode->m_payload.m_funName.size()>40)?"...":"")).c_str());

    // Write instrumentation flags
    if(pNode->m_payload.m_instrType != cv::instr::TYPE_GENERAL || pNode->m_payload.m_implType != cv::instr::IMPL_PLAIN)
    {
        printf("<");
        if(pNode->m_payload.m_instrType == cv::instr::TYPE_WRAPPER)
            printf("W");
        else if(pNode->m_payload.m_instrType == cv::instr::TYPE_FUN)
            printf("F");
        else if(pNode->m_payload.m_instrType == cv::instr::TYPE_MARKER)
            printf("MARK");

        if(pNode->m_payload.m_instrType != cv::instr::TYPE_GENERAL && pNode->m_payload.m_implType != cv::instr::IMPL_PLAIN)
            printf("_");

        if(pNode->m_payload.m_implType == cv::instr::IMPL_IPP)
            printf("IPP");
        else if(pNode->m_payload.m_implType == cv::instr::IMPL_OPENCL)
            printf("OCL");

        printf(">");
    }

    if(pNode->m_pParent)
    {
820 821
        printf(" - TC:%d C:%d", pNode->m_payload.m_threads, pNode->m_payload.m_counter);
        printf(" T:%.2fms", pNode->m_payload.getTotalMs());
822 823 824 825 826 827
        if(pNode->m_pParent->m_pParent)
            printf(" L:%.0f%% G:%.0f%%", calcLocalWeight(pNode), calcGlobalWeight(pNode));
    }
    printf("\n");

    {
828 829
        // Group childes by name
        for(size_t i = 1; i < pNode->m_childs.size(); i++)
830
        {
831 832 833
            if(pNode->m_childs[i-1]->m_payload.m_funName == pNode->m_childs[i]->m_payload.m_funName )
                continue;
            for(size_t j = i+1; j < pNode->m_childs.size(); j++)
834
            {
835
                if(pNode->m_childs[i-1]->m_payload.m_funName == pNode->m_childs[j]->m_payload.m_funName )
836
                {
837 838
                    cv::swap(pNode->m_childs[i], pNode->m_childs[j]);
                    i++;
839 840 841 842 843
                }
            }
        }
    }

844
    for(size_t i = 0; i < pNode->m_childs.size(); i++)
845
    {
846
        printShift(pNode->m_childs[i], pRoot);
847

848 849 850 851 852
        if(i == pNode->m_childs.size()-1)
            printf("\\---");
        else
            printf("|---");
        printNodeRec(pNode->m_childs[i], pRoot);
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
    }
}

template <typename T>
std::string to_string_with_precision(const T value, const int p = 3)
{
    std::ostringstream out;
    out << std::fixed << std::setprecision(p) << value;
    return out.str();
}

static cv::String nodeToString(cv::instr::InstrNode *pNode)
{
    cv::String string;
    if (pNode->m_payload.m_funName == "ROOT")
        string = pNode->m_payload.m_funName;
    else
    {
        string = "#";
872
        string += std::to_string((int)pNode->m_payload.m_instrType);
873 874 875 876 877 878 879 880 881 882 883 884 885 886
        string += pNode->m_payload.m_funName;
        string += " - L:";
        string += to_string_with_precision(calcLocalWeight(pNode));
        string += ", G:";
        string += to_string_with_precision(calcGlobalWeight(pNode));
    }
    string += "(";
    for(size_t i = 0; i < pNode->m_childs.size(); i++)
        string += nodeToString(pNode->m_childs[i]);
    string += ")";

    return string;
}

887
static uint64 getNodeTimeRec(cv::instr::InstrNode *pNode, cv::instr::TYPE type, cv::instr::IMPL impl)
888 889 890
{
    uint64 ticks = 0;

891 892 893 894 895
    if (pNode->m_pParent && (type < 0 || pNode->m_payload.m_instrType == type) && pNode->m_payload.m_implType == impl)
    {
        ticks = pNode->m_payload.m_ticksTotal;
        return ticks;
    }
896 897 898 899 900 901 902

    for(size_t i = 0; i < pNode->m_childs.size(); i++)
        ticks += getNodeTimeRec(pNode->m_childs[i], type, impl);

    return ticks;
}

903
static uint64 getImplTime(cv::instr::IMPL impl)
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
{
    uint64 ticks = 0;
    cv::instr::InstrNode *pRoot = cv::instr::getTrace();

    ticks = getNodeTimeRec(pRoot, cv::instr::TYPE_FUN, impl);

    return ticks;
}

static uint64 getTotalTime()
{
    uint64 ticks = 0;
    cv::instr::InstrNode *pRoot = cv::instr::getTrace();

    for(size_t i = 0; i < pRoot->m_childs.size(); i++)
919
        ticks += pRoot->m_childs[i]->m_payload.m_ticksTotal;
920 921 922 923 924 925 926 927 928

    return ticks;
}

::cv::String InstumentData::treeToString()
{
    cv::String string = nodeToString(cv::instr::getTrace());
    return string;
}
929

930 931
void InstumentData::printTree()
{
932 933
    printf("[ TRACE    ]\n");
    printNodeRec(cv::instr::getTrace(), cv::instr::getTrace());
934
#ifdef HAVE_IPP
935
    printf("\nIPP weight: %.1f%%", ((double)getImplTime(cv::instr::IMPL_IPP)*100/(double)getTotalTime()));
936 937
#endif
#ifdef HAVE_OPENCL
938
    printf("\nOPENCL weight: %.1f%%", ((double)getImplTime(cv::instr::IMPL_OPENCL)*100/(double)getTotalTime()));
939
#endif
940 941
    printf("\n[/TRACE    ]\n");
    fflush(stdout);
942 943
}
#endif
Daniil Osokin's avatar
Daniil Osokin committed
944 945 946 947 948 949 950 951

/*****************************************************************************************\
*                                   ::perf::TestBase
\*****************************************************************************************/


void TestBase::Init(int argc, const char* const argv[])
{
952 953 954 955 956 957 958 959
    std::vector<std::string> plain_only;
    plain_only.push_back("plain");
    TestBase::Init(plain_only, argc, argv);
}

void TestBase::Init(const std::vector<std::string> & availableImpls,
                 int argc, const char* const argv[])
{
960 961
    CV_TRACE_FUNCTION();

962 963 964
    available_impls = availableImpls;

    const std::string command_line_keys =
965 966 967 968 969 970 971 972 973 974 975
        "{   perf_max_outliers           |8        |percent of allowed outliers}"
        "{   perf_min_samples            |10       |minimal required numer of samples}"
        "{   perf_force_samples          |100      |force set maximum number of samples for all tests}"
        "{   perf_seed                   |809564   |seed for random numbers generator}"
        "{   perf_threads                |-1       |the number of worker threads, if parallel execution is enabled}"
        "{   perf_write_sanity           |false    |create new records for sanity checks}"
        "{   perf_verify_sanity          |false    |fail tests having no regression data for sanity checks}"
        "{   perf_impl                   |" + available_impls[0] +
                                                  "|the implementation variant of functions under test}"
        "{   perf_list_impls             |false    |list available implementation variants and exit}"
        "{   perf_run_cpu                |false    |deprecated, equivalent to --perf_impl=plain}"
976
        "{   perf_strategy               |default  |specifies performance measuring strategy: default, base or simple (weak restrictions)}"
977 978
        "{   perf_read_validation_results |        |specifies file name with performance results from previous run}"
        "{   perf_write_validation_results |       |specifies file name to write performance validation results}"
979
#ifdef __ANDROID__
980 981 982
        "{   perf_time_limit             |6.0      |default time limit for a single test (in seconds)}"
        "{   perf_affinity_mask          |0        |set affinity mask for the main thread}"
        "{   perf_log_power_checkpoints  |         |additional xml logging for power measurement}"
983
#else
984
        "{   perf_time_limit             |3.0      |default time limit for a single test (in seconds)}"
985
#endif
986
        "{   perf_max_deviation          |1.0      |}"
Ilya Lavrenov's avatar
Ilya Lavrenov committed
987 988
#ifdef HAVE_IPP
        "{   perf_ipp_check              |false    |check whether IPP works without failures}"
989 990 991
#endif
#ifdef CV_COLLECT_IMPL_DATA
        "{   perf_collect_impl           |false    |collect info about executed implementations}"
992 993
#endif
#ifdef ENABLE_INSTRUMENTATION
994
        "{   perf_instrument             |0        |instrument code to collect implementations trace: 1 - perform instrumentation; 2 - separate functions with the same name }"
Ilya Lavrenov's avatar
Ilya Lavrenov committed
995
#endif
996
        "{   help h                      |false    |print help info}"
997
#ifdef HAVE_CUDA
998
        "{   perf_cuda_device            |0        |run CUDA test suite onto specific CUDA capable device}"
999
        "{   perf_cuda_info_only         |false    |print an information about system and an available CUDA devices and then exit.}"
1000
#endif
1001
        "{ skip_unstable                 |false    |skip unstable tests }"
1002 1003
    ;

Daniil Osokin's avatar
Daniil Osokin committed
1004
    cv::CommandLineParser args(argc, argv, command_line_keys);
1005
    if (args.get<bool>("help"))
1006 1007 1008 1009 1010
    {
        args.printMessage();
        return;
    }

1011 1012
    ::testing::AddGlobalTestEnvironment(new PerfEnvironment);

1013
    param_impl          = args.get<bool>("perf_run_cpu") ? "plain" : args.get<std::string>("perf_impl");
1014 1015 1016 1017 1018 1019 1020
    std::string perf_strategy = args.get<std::string>("perf_strategy");
    if (perf_strategy == "default")
    {
        // nothing
    }
    else if (perf_strategy == "base")
    {
1021
        strategyForce = PERF_STRATEGY_BASE;
1022 1023 1024
    }
    else if (perf_strategy == "simple")
    {
1025
        strategyForce = PERF_STRATEGY_SIMPLE;
1026 1027 1028 1029 1030 1031
    }
    else
    {
        printf("No such strategy: %s\n", perf_strategy.c_str());
        exit(1);
    }
1032 1033
    param_max_outliers  = std::min(100., std::max(0., args.get<double>("perf_max_outliers")));
    param_min_samples   = std::max(1u, args.get<unsigned int>("perf_min_samples"));
Daniil Osokin's avatar
Daniil Osokin committed
1034
    param_max_deviation = std::max(0., args.get<double>("perf_max_deviation"));
1035
    param_seed          = args.get<unsigned int>("perf_seed");
1036
    param_time_limit    = std::max(0., args.get<double>("perf_time_limit"));
Daniil Osokin's avatar
Daniil Osokin committed
1037
    param_force_samples = args.get<unsigned int>("perf_force_samples");
1038 1039
    param_write_sanity  = args.get<bool>("perf_write_sanity");
    param_verify_sanity = args.get<bool>("perf_verify_sanity");
1040

Alexander Alekhin's avatar
Alexander Alekhin committed
1041
#ifdef HAVE_IPP
1042
    test_ipp_check      = !args.get<bool>("perf_ipp_check") ? getenv("OPENCV_IPP_CHECK") != NULL : true;
1043
#endif
1044
    testThreads         = args.get<int>("perf_threads");
1045
#ifdef CV_COLLECT_IMPL_DATA
1046
    param_collect_impl  = args.get<bool>("perf_collect_impl");
1047
#endif
1048
#ifdef ENABLE_INSTRUMENTATION
1049
    param_instrument    = args.get<int>("perf_instrument");
1050
#endif
1051
#ifdef __ANDROID__
1052 1053
    param_affinity_mask   = args.get<int>("perf_affinity_mask");
    log_power_checkpoints = args.has("perf_log_power_checkpoints");
Daniil Osokin's avatar
Daniil Osokin committed
1054 1055
#endif

1056
    bool param_list_impls = args.get<bool>("perf_list_impls");
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

    if (param_list_impls)
    {
        fputs("Available implementation variants:", stdout);
        for (size_t i = 0; i < available_impls.size(); ++i) {
            putchar(' ');
            fputs(available_impls[i].c_str(), stdout);
        }
        putchar('\n');
        exit(0);
    }

1069 1070 1071 1072 1073 1074
    if (std::find(available_impls.begin(), available_impls.end(), param_impl) == available_impls.end())
    {
        printf("No such implementation: %s\n", param_impl.c_str());
        exit(1);
    }

1075 1076 1077 1078 1079 1080
#ifdef CV_COLLECT_IMPL_DATA
    if(param_collect_impl)
        cv::setUseCollection(1);
    else
        cv::setUseCollection(0);
#endif
1081
#ifdef ENABLE_INSTRUMENTATION
1082 1083 1084 1085
    if(param_instrument > 0)
    {
        if(param_instrument == 2)
            cv::instr::setFlags(cv::instr::getFlags()|cv::instr::FLAGS_EXPAND_SAME_NAMES);
1086
        cv::instr::setUseInstrumentation(true);
1087
    }
1088 1089 1090
    else
        cv::instr::setUseInstrumentation(false);
#endif
1091

1092
#ifdef HAVE_CUDA
1093

1094
    bool printOnly        = args.get<bool>("perf_cuda_info_only");
1095 1096 1097

    if (printOnly)
        exit(0);
1098 1099
#endif

1100 1101
    skipUnstableTests = args.get<bool>("skip_unstable");

1102 1103 1104 1105
    if (available_impls.size() > 1)
        printf("[----------]\n[   INFO   ] \tImplementation variant: %s.\n[----------]\n", param_impl.c_str()), fflush(stdout);

#ifdef HAVE_CUDA
1106

1107
    param_cuda_device      = std::max(0, std::min(cv::cuda::getCudaEnabledDeviceCount(), args.get<int>("perf_cuda_device")));
1108

1109
    if (param_impl == "cuda")
1110
    {
1111
        cv::cuda::DeviceInfo info(param_cuda_device);
1112 1113
        if (!info.isCompatible())
        {
1114
            printf("[----------]\n[ FAILURE  ] \tDevice %s is NOT compatible with current CUDA module build.\n[----------]\n", info.name()), fflush(stdout);
1115 1116 1117
            exit(-1);
        }

1118
        cv::cuda::setDevice(param_cuda_device);
1119

1120
        printf("[----------]\n[ GPU INFO ] \tRun test suite on %s GPU.\n[----------]\n", info.name()), fflush(stdout);
1121
    }
1122 1123
#endif

1124
    {
1125
#ifndef WINRT
1126
        const char* path = getenv("OPENCV_PERF_VALIDATION_DIR");
1127 1128 1129
#else
        const char* path = OPENCV_PERF_VALIDATION_DIR;
#endif
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
        if (path)
            perf_validation_results_directory = path;
    }

    std::string fileName_perf_validation_results_src = args.get<std::string>("perf_read_validation_results");
    if (!fileName_perf_validation_results_src.empty())
    {
        perf_validation_enabled = true;
        loadPerfValidationResults(perf_validation_results_directory + fileName_perf_validation_results_src);
    }

    perf_validation_results_outfile = args.get<std::string>("perf_write_validation_results");
    if (!perf_validation_results_outfile.empty())
    {
        perf_validation_enabled = true;
        ::testing::AddGlobalTestEnvironment(new PerfValidationEnvironment());
    }

1148
    if (!args.check())
Daniil Osokin's avatar
Daniil Osokin committed
1149
    {
1150
        args.printErrors();
Alexander Alekhin's avatar
Alexander Alekhin committed
1151
        exit(1);
Daniil Osokin's avatar
Daniil Osokin committed
1152 1153 1154 1155 1156 1157 1158
    }

    timeLimitDefault = param_time_limit == 0.0 ? 1 : (int64)(param_time_limit * cv::getTickFrequency());
    iterationsLimitDefault = param_force_samples == 0 ? (unsigned)(-1) : param_force_samples;
    _timeadjustment = _calibrate();
}

1159 1160 1161
void TestBase::RecordRunParameters()
{
    ::testing::Test::RecordProperty("cv_implementation", param_impl);
1162
    ::testing::Test::RecordProperty("cv_num_threads", testThreads);
1163 1164 1165 1166

#ifdef HAVE_CUDA
    if (param_impl == "cuda")
    {
1167
        cv::cuda::DeviceInfo info(param_cuda_device);
1168 1169 1170
        ::testing::Test::RecordProperty("cv_cuda_gpu", info.name());
    }
#endif
1171
}
1172 1173 1174 1175 1176 1177

std::string TestBase::getSelectedImpl()
{
    return param_impl;
}

1178
enum PERF_STRATEGY TestBase::setModulePerformanceStrategy(enum PERF_STRATEGY strategy)
1179
{
1180 1181 1182
    enum PERF_STRATEGY ret = strategyModule;
    strategyModule = strategy;
    return ret;
1183 1184
}

1185
enum PERF_STRATEGY TestBase::getCurrentModulePerformanceStrategy()
1186
{
1187
    return strategyForce == PERF_STRATEGY_DEFAULT ? strategyModule : strategyForce;
1188 1189
}

1190

Daniil Osokin's avatar
Daniil Osokin committed
1191 1192
int64 TestBase::_calibrate()
{
1193
    CV_TRACE_FUNCTION();
Daniil Osokin's avatar
Daniil Osokin committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    class _helper : public ::perf::TestBase
    {
        public:
        performance_metrics& getMetrics() { return calcMetrics(); }
        virtual void TestBody() {}
        virtual void PerfTestBody()
        {
            //the whole system warmup
            SetUp();
            cv::Mat a(2048, 2048, CV_32S, cv::Scalar(1));
            cv::Mat b(2048, 2048, CV_32S, cv::Scalar(2));
            declare.time(30);
            double s = 0;
1207
            for(declare.iterations(20); next() && startTimer(); stopTimer())
Daniil Osokin's avatar
Daniil Osokin committed
1208 1209 1210 1211 1212
                s+=a.dot(b);
            declare.time(s);

            //self calibration
            SetUp();
1213
            for(declare.iterations(1000); next() && startTimer(); stopTimer()){}
Daniil Osokin's avatar
Daniil Osokin committed
1214 1215 1216
        }
    };

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    // Initialize ThreadPool
    class _dummyParallel : public ParallelLoopBody
    {
    public:
       void operator()(const cv::Range& range) const
       {
           // nothing
           CV_UNUSED(range);
       }
    };
    parallel_for_(cv::Range(0, 1000), _dummyParallel());

Daniil Osokin's avatar
Daniil Osokin committed
1229 1230 1231 1232
    _timeadjustment = 0;
    _helper h;
    h.PerfTestBody();
    double compensation = h.getMetrics().min;
1233
    if (getCurrentModulePerformanceStrategy() == PERF_STRATEGY_SIMPLE)
1234 1235 1236 1237
    {
        CV_Assert(compensation < 0.01 * cv::getTickFrequency());
        compensation = 0.0f; // simple strategy doesn't require any compensation
    }
Daniil Osokin's avatar
Daniil Osokin committed
1238 1239 1240 1241 1242 1243 1244 1245
    LOGD("Time compensation is %.0f", compensation);
    return (int64)compensation;
}

#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4355)  // 'this' : used in base member initializer list
#endif
1246
TestBase::TestBase(): testStrategy(PERF_STRATEGY_DEFAULT), declare(this)
Daniil Osokin's avatar
Daniil Osokin committed
1247
{
1248 1249
    lastTime = totalTime = timeLimit = 0;
    nIters = currentIter = runsPerIteration = 0;
1250
    minIters = param_min_samples;
1251
    verified = false;
1252
    perfValidationStage = 0;
Daniil Osokin's avatar
Daniil Osokin committed
1253 1254 1255 1256 1257 1258
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif


1259
void TestBase::declareArray(SizeVector& sizes, cv::InputOutputArray a, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
{
    if (!a.empty())
    {
        sizes.push_back(std::pair<int, cv::Size>(getSizeInBytes(a), getSize(a)));
        warmup(a, wtype);
    }
    else if (a.kind() != cv::_InputArray::NONE)
        ADD_FAILURE() << "  Uninitialized input/output parameters are not allowed for performance tests";
}

1270
void TestBase::warmup(cv::InputOutputArray a, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
1271
{
1272
    CV_TRACE_FUNCTION();
1273 1274
    if (a.empty())
        return;
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    else if (a.isUMat())
    {
        if (wtype == WARMUP_RNG || wtype == WARMUP_WRITE)
        {
            int depth = a.depth();
            if (depth == CV_8U)
                cv::randu(a, 0, 256);
            else if (depth == CV_8S)
                cv::randu(a, -128, 128);
            else if (depth == CV_16U)
                cv::randu(a, 0, 1024);
            else if (depth == CV_32F || depth == CV_64F)
                cv::randu(a, -1.0, 1.0);
            else if (depth == CV_16S || depth == CV_32S)
                cv::randu(a, -4096, 4096);
            else
                CV_Error(cv::Error::StsUnsupportedFormat, "Unsupported format");
        }
1293
        return;
1294 1295
    }
    else if (a.kind() != cv::_InputArray::STD_VECTOR_MAT && a.kind() != cv::_InputArray::STD_VECTOR_VECTOR)
Daniil Osokin's avatar
Daniil Osokin committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
        warmup_impl(a.getMat(), wtype);
    else
    {
        size_t total = a.total();
        for (size_t i = 0; i < total; ++i)
            warmup_impl(a.getMat((int)i), wtype);
    }
}

int TestBase::getSizeInBytes(cv::InputArray a)
{
    if (a.empty()) return 0;
    int total = (int)a.total();
    if (a.kind() != cv::_InputArray::STD_VECTOR_MAT && a.kind() != cv::_InputArray::STD_VECTOR_VECTOR)
        return total * CV_ELEM_SIZE(a.type());

    int size = 0;
    for (int i = 0; i < total; ++i)
        size += (int)a.total(i) * CV_ELEM_SIZE(a.type(i));

    return size;
}

cv::Size TestBase::getSize(cv::InputArray a)
{
    if (a.kind() != cv::_InputArray::STD_VECTOR_MAT && a.kind() != cv::_InputArray::STD_VECTOR_VECTOR)
        return a.size();
    return cv::Size();
}

1326 1327 1328 1329 1330 1331 1332 1333
PERF_STRATEGY TestBase::getCurrentPerformanceStrategy() const
{
    if (strategyForce == PERF_STRATEGY_DEFAULT)
        return (testStrategy == PERF_STRATEGY_DEFAULT) ? strategyModule : testStrategy;
    else
        return strategyForce;
}

Daniil Osokin's avatar
Daniil Osokin committed
1334 1335
bool TestBase::next()
{
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
    static int64 lastActivityPrintTime = 0;

    if (currentIter != (unsigned int)-1)
    {
        if (currentIter + 1 != times.size())
            ADD_FAILURE() << "  next() is called before stopTimer()";
    }
    else
    {
        lastActivityPrintTime = 0;
        metrics.clear();
    }

1349
    cv::theRNG().state = param_seed; //this rng should generate same numbers for each run
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    ++currentIter;

    bool has_next = false;

    do {
        assert(currentIter == times.size());
        if (currentIter == 0)
        {
            has_next = true;
            break;
        }

1362
        if (getCurrentPerformanceStrategy() == PERF_STRATEGY_BASE)
1363 1364 1365 1366 1367
        {
            has_next = currentIter < nIters && totalTime < timeLimit;
        }
        else
        {
1368
            assert(getCurrentPerformanceStrategy() == PERF_STRATEGY_SIMPLE);
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
            if (totalTime - lastActivityPrintTime >= cv::getTickFrequency() * 10)
            {
                std::cout << '.' << std::endl;
                lastActivityPrintTime = totalTime;
            }
            if (currentIter >= nIters)
            {
                has_next = false;
                break;
            }
1379
            if (currentIter < minIters)
1380 1381 1382 1383 1384 1385 1386 1387
            {
                has_next = true;
                break;
            }

            calcMetrics();

            if (fabs(metrics.mean) > 1e-6)
1388
                has_next = metrics.stddev > perf_stability_criteria * fabs(metrics.mean);
1389 1390 1391 1392
            else
                has_next = true;
        }
    } while (false);
1393

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
    if (perf_validation_enabled && !has_next)
    {
        calcMetrics();
        double median_ms = metrics.median * 1000.0f / metrics.frequency;

        const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info();
        std::string name = (test_info == 0) ? "" :
                std::string(test_info->test_case_name()) + "--" + test_info->name();

        if (!perf_validation_results.empty() && !name.empty())
        {
            std::map<std::string, float>::iterator i = perf_validation_results.find(name);
            bool isSame = false;
            bool found = false;
            bool grow = false;
            if (i != perf_validation_results.end())
            {
                found = true;
                double prev_result = i->second;
                grow = median_ms > prev_result;
                isSame = fabs(median_ms - prev_result) <= perf_validation_criteria * fabs(median_ms);
                if (!isSame)
                {
                    if (perfValidationStage == 0)
                    {
                        printf("Performance is changed (samples = %d, median):\n    %.2f ms (current)\n    %.2f ms (previous)\n", (int)times.size(), median_ms, prev_result);
                    }
                }
            }
            else
            {
                if (perfValidationStage == 0)
                    printf("New performance result is detected\n");
            }
            if (!isSame)
            {
                if (perfValidationStage < 2)
                {
                    if (perfValidationStage == 0 && currentIter <= minIters * 3 && currentIter < nIters)
                    {
                        unsigned int new_minIters = std::max(minIters * 5, currentIter * 3);
                        printf("Increase minIters from %u to %u\n", minIters, new_minIters);
                        minIters = new_minIters;
                        has_next = true;
                        perfValidationStage++;
                    }
                    else if (found && currentIter >= nIters &&
                            median_ms > perf_validation_time_threshold_ms &&
                            (grow || metrics.stddev > perf_stability_criteria * fabs(metrics.mean)))
                    {
1444
                        CV_TRACE_REGION("idle_delay");
1445 1446
                        printf("Performance is unstable, it may be a result of overheat problems\n");
                        printf("Idle delay for %d ms... \n", perf_validation_idle_delay_ms);
1447
#if defined _WIN32
1448
#ifndef WINRT_8_0
1449
                        Sleep(perf_validation_idle_delay_ms);
1450 1451 1452
#else
                        WaitForSingleObjectEx(GetCurrentThread(), perf_validation_idle_delay_ms, FALSE);
#endif
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
#else
                        usleep(perf_validation_idle_delay_ms * 1000);
#endif
                        has_next = true;
                        minIters = std::min(minIters * 5, nIters);
                        // reset collected samples
                        currentIter = 0;
                        times.clear();
                        metrics.clear();
                        perfValidationStage += 2;
                    }
                    if (!has_next)
                    {
                        printf("Assume that current result is valid\n");
                    }
                }
                else
                {
                    printf("Re-measured performance result: %.2f ms\n", median_ms);
                }
            }
        }

        if (!has_next && !name.empty())
        {
            savePerfValidationResult(name, (float)median_ms);
        }
    }

1482
#ifdef __ANDROID__
Daniil Osokin's avatar
Daniil Osokin committed
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
    if (log_power_checkpoints)
    {
        timeval tim;
        gettimeofday(&tim, NULL);
        unsigned long long t1 = tim.tv_sec * 1000LLU + (unsigned long long)(tim.tv_usec / 1000.f);

        if (currentIter == 1) RecordProperty("test_start", cv::format("%llu",t1).c_str());
        if (!has_next) RecordProperty("test_complete", cv::format("%llu",t1).c_str());
    }
#endif
1493

Daniil Osokin's avatar
Daniil Osokin committed
1494 1495 1496
    return has_next;
}

1497
void TestBase::warmup_impl(cv::Mat m, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
{
    switch(wtype)
    {
    case WARMUP_READ:
        cv::sum(m.reshape(1));
        return;
    case WARMUP_WRITE:
        m.reshape(1).setTo(cv::Scalar::all(0));
        return;
    case WARMUP_RNG:
        randu(m);
        return;
    default:
        return;
    }
}

unsigned int TestBase::getTotalInputSize() const
{
    unsigned int res = 0;
    for (SizeVector::const_iterator i = inputData.begin(); i != inputData.end(); ++i)
        res += i->first;
    return res;
}

unsigned int TestBase::getTotalOutputSize() const
{
    unsigned int res = 0;
    for (SizeVector::const_iterator i = outputData.begin(); i != outputData.end(); ++i)
        res += i->first;
    return res;
}

1531
bool TestBase::startTimer()
Daniil Osokin's avatar
Daniil Osokin committed
1532
{
1533 1534 1535 1536 1537 1538 1539
#ifdef ENABLE_INSTRUMENTATION
    if(currentIter == 0)
    {
        cv::instr::setFlags(cv::instr::getFlags()|cv::instr::FLAGS_MAPPING); // enable mapping for the first run
        cv::instr::resetTrace();
    }
#endif
Daniil Osokin's avatar
Daniil Osokin committed
1540
    lastTime = cv::getTickCount();
1541
    return true; // dummy true for conditional loop
Daniil Osokin's avatar
Daniil Osokin committed
1542 1543 1544 1545 1546 1547
}

void TestBase::stopTimer()
{
    int64 time = cv::getTickCount();
    if (lastTime == 0)
1548
        ADD_FAILURE() << "  stopTimer() is called before startTimer()/next()";
Daniil Osokin's avatar
Daniil Osokin committed
1549 1550 1551 1552 1553 1554
    lastTime = time - lastTime;
    totalTime += lastTime;
    lastTime -= _timeadjustment;
    if (lastTime < 0) lastTime = 0;
    times.push_back(lastTime);
    lastTime = 0;
1555 1556 1557 1558

#ifdef ENABLE_INSTRUMENTATION
    cv::instr::setFlags(cv::instr::getFlags()&~cv::instr::FLAGS_MAPPING); // disable mapping to decrease overhead for +1 run
#endif
Daniil Osokin's avatar
Daniil Osokin committed
1559 1560 1561 1562
}

performance_metrics& TestBase::calcMetrics()
{
1563
    CV_Assert(metrics.samples <= (unsigned int)currentIter);
Daniil Osokin's avatar
Daniil Osokin committed
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
    if ((metrics.samples == (unsigned int)currentIter) || times.size() == 0)
        return metrics;

    metrics.bytesIn = getTotalInputSize();
    metrics.bytesOut = getTotalOutputSize();
    metrics.frequency = cv::getTickFrequency();
    metrics.samples = (unsigned int)times.size();
    metrics.outliers = 0;

    if (metrics.terminationReason != performance_metrics::TERM_INTERRUPT && metrics.terminationReason != performance_metrics::TERM_EXCEPTION)
    {
        if (currentIter == nIters)
            metrics.terminationReason = performance_metrics::TERM_ITERATIONS;
        else if (totalTime >= timeLimit)
            metrics.terminationReason = performance_metrics::TERM_TIME;
        else
            metrics.terminationReason = performance_metrics::TERM_UNKNOWN;
    }

    std::sort(times.begin(), times.end());

1585 1586
    TimeVector::const_iterator start = times.begin();
    TimeVector::const_iterator end = times.end();
Daniil Osokin's avatar
Daniil Osokin committed
1587

1588
    if (getCurrentPerformanceStrategy() == PERF_STRATEGY_BASE)
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    {
        //estimate mean and stddev for log(time)
        double gmean = 0;
        double gstddev = 0;
        int n = 0;
        for(TimeVector::const_iterator i = times.begin(); i != times.end(); ++i)
        {
            double x = static_cast<double>(*i)/runsPerIteration;
            if (x < DBL_EPSILON) continue;
            double lx = log(x);
Daniil Osokin's avatar
Daniil Osokin committed
1599

1600 1601 1602 1603 1604
            ++n;
            double delta = lx - gmean;
            gmean += delta / n;
            gstddev += delta * (lx - gmean);
        }
Daniil Osokin's avatar
Daniil Osokin committed
1605

1606
        gstddev = n > 1 ? sqrt(gstddev / (n - 1)) : 0;
Daniil Osokin's avatar
Daniil Osokin committed
1607

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
        //filter outliers assuming log-normal distribution
        //http://stackoverflow.com/questions/1867426/modeling-distribution-of-performance-measurements
        if (gstddev > DBL_EPSILON)
        {
            double minout = exp(gmean - 3 * gstddev) * runsPerIteration;
            double maxout = exp(gmean + 3 * gstddev) * runsPerIteration;
            while(*start < minout) ++start, ++metrics.outliers;
            do --end, ++metrics.outliers; while(*end > maxout);
            ++end, --metrics.outliers;
        }
    }
1619
    else if (getCurrentPerformanceStrategy() == PERF_STRATEGY_SIMPLE)
1620 1621 1622 1623 1624 1625
    {
        metrics.outliers = static_cast<int>(times.size() * param_max_outliers / 100);
        for (unsigned int i = 0; i < metrics.outliers; i++)
            --end;
    }
    else
Daniil Osokin's avatar
Daniil Osokin committed
1626
    {
1627
        assert(false);
Daniil Osokin's avatar
Daniil Osokin committed
1628 1629
    }

1630 1631
    int offset = static_cast<int>(start - times.begin());

Daniil Osokin's avatar
Daniil Osokin committed
1632 1633
    metrics.min = static_cast<double>(*start)/runsPerIteration;
    //calc final metrics
1634 1635 1636
    unsigned int n = 0;
    double gmean = 0;
    double gstddev = 0;
Daniil Osokin's avatar
Daniil Osokin committed
1637 1638
    double mean = 0;
    double stddev = 0;
1639
    unsigned int m = 0;
Daniil Osokin's avatar
Daniil Osokin committed
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
    for(; start != end; ++start)
    {
        double x = static_cast<double>(*start)/runsPerIteration;
        if (x > DBL_EPSILON)
        {
            double lx = log(x);
            ++m;
            double gdelta = lx - gmean;
            gmean += gdelta / m;
            gstddev += gdelta * (lx - gmean);
        }
        ++n;
        double delta = x - mean;
        mean += delta / n;
        stddev += delta * (x - mean);
    }

    metrics.mean = mean;
    metrics.gmean = exp(gmean);
    metrics.gstddev = m > 1 ? sqrt(gstddev / (m - 1)) : 0;
    metrics.stddev = n > 1 ? sqrt(stddev / (n - 1)) : 0;
1661
    metrics.median = (n % 2
Daniil Osokin's avatar
Daniil Osokin committed
1662
            ? (double)times[offset + n / 2]
1663 1664
            : 0.5 * (times[offset + n / 2] + times[offset + n / 2 - 1])
            ) / runsPerIteration;
Daniil Osokin's avatar
Daniil Osokin committed
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677

    return metrics;
}

void TestBase::validateMetrics()
{
    performance_metrics& m = calcMetrics();

    if (HasFailure()) return;

    ASSERT_GE(m.samples, 1u)
      << "  No time measurements was performed.\nstartTimer() and stopTimer() commands are required for performance tests.";

1678
    if (getCurrentPerformanceStrategy() == PERF_STRATEGY_BASE)
1679 1680 1681 1682 1683 1684 1685 1686 1687
    {
        EXPECT_GE(m.samples, param_min_samples)
          << "  Only a few samples are collected.\nPlease increase number of iterations or/and time limit to get reliable performance measurements.";

        if (m.gstddev > DBL_EPSILON)
        {
            EXPECT_GT(/*m.gmean * */1., /*m.gmean * */ 2 * sinh(m.gstddev * param_max_deviation))
              << "  Test results are not reliable ((mean-sigma,mean+sigma) deviation interval is greater than measured time interval).";
        }
Daniil Osokin's avatar
Daniil Osokin committed
1688

1689 1690 1691
        EXPECT_LE(m.outliers, std::max((unsigned int)cvCeil(m.samples * param_max_outliers / 100.), 1u))
          << "  Test results are not reliable (too many outliers).";
    }
1692
    else if (getCurrentPerformanceStrategy() == PERF_STRATEGY_SIMPLE)
Daniil Osokin's avatar
Daniil Osokin committed
1693
    {
1694
        double mean = metrics.mean * 1000.0f / metrics.frequency;
1695
        double median = metrics.median * 1000.0f / metrics.frequency;
1696
        double min_value = metrics.min * 1000.0f / metrics.frequency;
1697 1698
        double stddev = metrics.stddev * 1000.0f / metrics.frequency;
        double percents = stddev / mean * 100.f;
1699
        printf("[ PERFSTAT ]    (samples=%d   mean=%.2f   median=%.2f   min=%.2f   stddev=%.2f (%.1f%%))\n", (int)metrics.samples, mean, median, min_value, stddev, percents);
1700 1701 1702 1703
    }
    else
    {
        assert(false);
Daniil Osokin's avatar
Daniil Osokin committed
1704 1705 1706 1707 1708
    }
}

void TestBase::reportMetrics(bool toJUnitXML)
{
1709 1710
    CV_TRACE_FUNCTION();

Daniil Osokin's avatar
Daniil Osokin committed
1711 1712
    performance_metrics& m = calcMetrics();

1713 1714 1715 1716 1717 1718 1719
    CV_TRACE_ARG_VALUE(samples, "samples", (int64)m.samples);
    CV_TRACE_ARG_VALUE(outliers, "outliers", (int64)m.outliers);
    CV_TRACE_ARG_VALUE(median, "mean_ms", (double)(m.mean * 1000.0f / metrics.frequency));
    CV_TRACE_ARG_VALUE(median, "median_ms", (double)(m.median * 1000.0f / metrics.frequency));
    CV_TRACE_ARG_VALUE(stddev, "stddev_ms", (double)(m.stddev * 1000.0f / metrics.frequency));
    CV_TRACE_ARG_VALUE(stddev_percents, "stddev_percents", (double)(m.stddev / (double)m.mean * 100.0f));

1720 1721 1722 1723 1724 1725 1726 1727
    if (m.terminationReason == performance_metrics::TERM_SKIP_TEST)
    {
        if (toJUnitXML)
        {
            RecordProperty("custom_status", "skipped");
        }
    }
    else if (toJUnitXML)
Daniil Osokin's avatar
Daniil Osokin committed
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
    {
        RecordProperty("bytesIn", (int)m.bytesIn);
        RecordProperty("bytesOut", (int)m.bytesOut);
        RecordProperty("term", m.terminationReason);
        RecordProperty("samples", (int)m.samples);
        RecordProperty("outliers", (int)m.outliers);
        RecordProperty("frequency", cv::format("%.0f", m.frequency).c_str());
        RecordProperty("min", cv::format("%.0f", m.min).c_str());
        RecordProperty("median", cv::format("%.0f", m.median).c_str());
        RecordProperty("gmean", cv::format("%.0f", m.gmean).c_str());
        RecordProperty("gstddev", cv::format("%.6f", m.gstddev).c_str());
        RecordProperty("mean", cv::format("%.0f", m.mean).c_str());
        RecordProperty("stddev", cv::format("%.0f", m.stddev).c_str());
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
#ifdef ENABLE_INSTRUMENTATION
        if(cv::instr::useInstrumentation())
        {
            cv::String tree = InstumentData::treeToString();
            RecordProperty("functions_hierarchy", tree.c_str());
            RecordProperty("total_ipp_weight",    cv::format("%.1f", ((double)getImplTime(cv::instr::IMPL_IPP)*100/(double)getTotalTime())));
            RecordProperty("total_opencl_weight", cv::format("%.1f", ((double)getImplTime(cv::instr::IMPL_OPENCL)*100/(double)getTotalTime())));
            cv::instr::resetTrace();
        }
#endif
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
#ifdef CV_COLLECT_IMPL_DATA
        if(param_collect_impl)
        {
            RecordProperty("impl_ipp", (int)(implConf.ipp || implConf.icv));
            RecordProperty("impl_ocl", (int)implConf.ocl);
            RecordProperty("impl_plain", (int)implConf.plain);

            std::string rec_line;
            std::vector<cv::String> rec;
            rec_line.clear();
            rec = implConf.GetCallsForImpl(CV_IMPL_IPP|CV_IMPL_MT);
            for(int i=0; i<rec.size();i++ ){rec_line += rec[i].c_str(); rec_line += " ";}
            rec = implConf.GetCallsForImpl(CV_IMPL_IPP);
            for(int i=0; i<rec.size();i++ ){rec_line += rec[i].c_str(); rec_line += " ";}
            RecordProperty("impl_rec_ipp", rec_line.c_str());

            rec_line.clear();
            rec = implConf.GetCallsForImpl(CV_IMPL_OCL);
            for(int i=0; i<rec.size();i++ ){rec_line += rec[i].c_str(); rec_line += " ";}
            RecordProperty("impl_rec_ocl", rec_line.c_str());
        }
#endif
Daniil Osokin's avatar
Daniil Osokin committed
1773 1774 1775 1776 1777 1778 1779
    }
    else
    {
        const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info();
        const char* type_param = test_info->type_param();
        const char* value_param = test_info->value_param();

1780
#if defined(__ANDROID__) && defined(USE_ANDROID_LOGGING)
Daniil Osokin's avatar
Daniil Osokin committed
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
        LOGD("[ FAILED   ] %s.%s", test_info->test_case_name(), test_info->name());
#endif

        if (type_param)  LOGD("type      = %11s", type_param);
        if (value_param) LOGD("params    = %11s", value_param);

        switch (m.terminationReason)
        {
        case performance_metrics::TERM_ITERATIONS:
            LOGD("termination reason:  reached maximum number of iterations");
            break;
        case performance_metrics::TERM_TIME:
            LOGD("termination reason:  reached time limit");
            break;
        case performance_metrics::TERM_INTERRUPT:
            LOGD("termination reason:  aborted by the performance testing framework");
            break;
        case performance_metrics::TERM_EXCEPTION:
            LOGD("termination reason:  unhandled exception");
            break;
        case performance_metrics::TERM_UNKNOWN:
        default:
            LOGD("termination reason:  unknown");
            break;
        };

1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
#ifdef CV_COLLECT_IMPL_DATA
        if(param_collect_impl)
        {
            LOGD("impl_ipp =%11d", (int)(implConf.ipp || implConf.icv));
            LOGD("impl_ocl =%11d", (int)implConf.ocl);
            LOGD("impl_plain =%11d", (int)implConf.plain);

            std::string rec_line;
            std::vector<cv::String> rec;
            rec_line.clear();
            rec = implConf.GetCallsForImpl(CV_IMPL_IPP|CV_IMPL_MT);
            for(int i=0; i<rec.size();i++ ){rec_line += rec[i].c_str(); rec_line += " ";}
            rec = implConf.GetCallsForImpl(CV_IMPL_IPP);
            for(int i=0; i<rec.size();i++ ){rec_line += rec[i].c_str(); rec_line += " ";}
            LOGD("impl_rec_ipp =%s", rec_line.c_str());

            rec_line.clear();
            rec = implConf.GetCallsForImpl(CV_IMPL_OCL);
            for(int i=0; i<rec.size();i++ ){rec_line += rec[i].c_str(); rec_line += " ";}
            LOGD("impl_rec_ocl =%s", rec_line.c_str());
        }
#endif

Daniil Osokin's avatar
Daniil Osokin committed
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
        LOGD("bytesIn   =%11lu", (unsigned long)m.bytesIn);
        LOGD("bytesOut  =%11lu", (unsigned long)m.bytesOut);
        if (nIters == (unsigned int)-1 || m.terminationReason == performance_metrics::TERM_ITERATIONS)
            LOGD("samples   =%11u",  m.samples);
        else
            LOGD("samples   =%11u of %u", m.samples, nIters);
        LOGD("outliers  =%11u", m.outliers);
        LOGD("frequency =%11.0f", m.frequency);
        if (m.samples > 0)
        {
            LOGD("min       =%11.0f = %.2fms", m.min, m.min * 1e3 / m.frequency);
            LOGD("median    =%11.0f = %.2fms", m.median, m.median * 1e3 / m.frequency);
            LOGD("gmean     =%11.0f = %.2fms", m.gmean, m.gmean * 1e3 / m.frequency);
            LOGD("gstddev   =%11.8f = %.2fms for 97%% dispersion interval", m.gstddev, m.gmean * 2 * sinh(m.gstddev * 3) * 1e3 / m.frequency);
            LOGD("mean      =%11.0f = %.2fms", m.mean, m.mean * 1e3 / m.frequency);
            LOGD("stddev    =%11.0f = %.2fms", m.stddev, m.stddev * 1e3 / m.frequency);
        }
    }
}

void TestBase::SetUp()
{
1852 1853
    cv::theRNG().state = param_seed; // this rng should generate same numbers for each run

1854 1855
    if (testThreads >= 0)
        cv::setNumThreads(testThreads);
1856 1857
    else
        cv::setNumThreads(-1);
1858

1859
#ifdef __ANDROID__
Daniil Osokin's avatar
Daniil Osokin committed
1860 1861 1862
    if (param_affinity_mask)
        setCurrentThreadAffinityMask(param_affinity_mask);
#endif
1863

1864
    verified = false;
Daniil Osokin's avatar
Daniil Osokin committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
    lastTime = 0;
    totalTime = 0;
    runsPerIteration = 1;
    nIters = iterationsLimitDefault;
    currentIter = (unsigned int)-1;
    timeLimit = timeLimitDefault;
    times.clear();
}

void TestBase::TearDown()
{
1876 1877 1878 1879 1880
    if (metrics.terminationReason == performance_metrics::TERM_SKIP_TEST)
    {
        LOGI("\tTest was skipped");
        GTEST_SUCCEED() << "Test was skipped";
    }
Daniil Osokin's avatar
Daniil Osokin committed
1881 1882
    else
    {
1883 1884 1885 1886 1887 1888 1889
        if (!HasFailure() && !verified)
            ADD_FAILURE() << "The test has no sanity checks. There should be at least one check at the end of performance test.";

        validateMetrics();
        if (HasFailure())
        {
            reportMetrics(false);
1890 1891 1892 1893 1894

#ifdef ENABLE_INSTRUMENTATION
            if(cv::instr::useInstrumentation())
                InstumentData::printTree();
#endif
1895 1896
            return;
        }
Daniil Osokin's avatar
Daniil Osokin committed
1897
    }
1898

1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
#ifdef CV_COLLECT_IMPL_DATA
    if(param_collect_impl)
    {
        implConf.ShapeUp();
        printf("[ I. FLAGS ] \t");
        if(implConf.ipp_mt)
        {
            if(implConf.icv) {printf("ICV_MT "); std::vector<cv::String> fun = implConf.GetCallsForImpl(CV_IMPL_IPP|CV_IMPL_MT); printf("("); for(int i=0; i<fun.size();i++ ){printf("%s ", fun[i].c_str());} printf(") "); }
            if(implConf.ipp) {printf("IPP_MT "); std::vector<cv::String> fun = implConf.GetCallsForImpl(CV_IMPL_IPP|CV_IMPL_MT); printf("("); for(int i=0; i<fun.size();i++ ){printf("%s ", fun[i].c_str());} printf(") "); }
        }
        else
        {
            if(implConf.icv) {printf("ICV "); std::vector<cv::String> fun = implConf.GetCallsForImpl(CV_IMPL_IPP); printf("("); for(int i=0; i<fun.size();i++ ){printf("%s ", fun[i].c_str());} printf(") "); }
            if(implConf.ipp) {printf("IPP "); std::vector<cv::String> fun = implConf.GetCallsForImpl(CV_IMPL_IPP); printf("("); for(int i=0; i<fun.size();i++ ){printf("%s ", fun[i].c_str());} printf(") "); }
        }
        if(implConf.ocl) {printf("OCL "); std::vector<cv::String> fun = implConf.GetCallsForImpl(CV_IMPL_OCL); printf("("); for(int i=0; i<fun.size();i++ ){printf("%s ", fun[i].c_str());} printf(") "); }
        if(implConf.plain) printf("PLAIN ");
        if(!(implConf.ipp_mt || implConf.icv || implConf.ipp || implConf.ocl || implConf.plain))
            printf("ERROR ");
        printf("\n");
        fflush(stdout);
    }
#endif
1922 1923 1924 1925 1926 1927

#ifdef ENABLE_INSTRUMENTATION
    if(cv::instr::useInstrumentation())
        InstumentData::printTree();
#endif

1928
    reportMetrics(true);
Daniil Osokin's avatar
Daniil Osokin committed
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
}

std::string TestBase::getDataPath(const std::string& relativePath)
{
    if (relativePath.empty())
    {
        ADD_FAILURE() << "  Bad path to test resource";
        throw PerfEarlyExitException();
    }

1939
#ifndef WINRT
Daniil Osokin's avatar
Daniil Osokin committed
1940
    const char *data_path_dir = getenv("OPENCV_TEST_DATA_PATH");
1941 1942 1943
#else
    const char *data_path_dir = OPENCV_TEST_DATA_PATH;
#endif
Daniil Osokin's avatar
Daniil Osokin committed
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
    const char *path_separator = "/";

    std::string path;
    if (data_path_dir)
    {
        int len = (int)strlen(data_path_dir) - 1;
        if (len < 0) len = 0;
        path = (data_path_dir[0] == 0 ? std::string(".") : std::string(data_path_dir))
                + (data_path_dir[len] == '/' || data_path_dir[len] == '\\' ? "" : path_separator);
    }
    else
    {
        path = ".";
        path += path_separator;
    }

    if (relativePath[0] == '/' || relativePath[0] == '\\')
        path += relativePath.substr(1);
    else
        path += relativePath;

    FILE* fp = fopen(path.c_str(), "r");
    if (fp)
        fclose(fp);
    else
    {
        ADD_FAILURE() << "  Requested file \"" << path << "\" does not exist.";
        throw PerfEarlyExitException();
    }
    return path;
}

void TestBase::RunPerfTestBody()
{
    try
    {
1980 1981 1982 1983
#ifdef CV_COLLECT_IMPL_DATA
        if(param_collect_impl)
            implConf.Reset();
#endif
Daniil Osokin's avatar
Daniil Osokin committed
1984
        this->PerfTestBody();
1985 1986 1987 1988
#ifdef CV_COLLECT_IMPL_DATA
        if(param_collect_impl)
            implConf.GetImpl();
#endif
Daniil Osokin's avatar
Daniil Osokin committed
1989
    }
1990 1991 1992 1993 1994
    catch(SkipTestException&)
    {
        metrics.terminationReason = performance_metrics::TERM_SKIP_TEST;
        return;
    }
1995 1996 1997 1998 1999
    catch(PerfSkipTestException&)
    {
        metrics.terminationReason = performance_metrics::TERM_SKIP_TEST;
        return;
    }
2000
    catch(PerfEarlyExitException&)
Daniil Osokin's avatar
Daniil Osokin committed
2001 2002 2003 2004
    {
        metrics.terminationReason = performance_metrics::TERM_INTERRUPT;
        return;//no additional failure logging
    }
2005
    catch(cv::Exception& e)
Daniil Osokin's avatar
Daniil Osokin committed
2006 2007
    {
        metrics.terminationReason = performance_metrics::TERM_EXCEPTION;
2008
        #ifdef HAVE_CUDA
2009
            if (e.code == cv::Error::GpuApiCallError)
2010
                cv::cuda::resetDevice();
2011
        #endif
2012 2013
        FAIL() << "Expected: PerfTestBody() doesn't throw an exception.\n  Actual: it throws cv::Exception:\n  " << e.what();
    }
2014
    catch(std::exception& e)
2015 2016 2017
    {
        metrics.terminationReason = performance_metrics::TERM_EXCEPTION;
        FAIL() << "Expected: PerfTestBody() doesn't throw an exception.\n  Actual: it throws std::exception:\n  " << e.what();
Daniil Osokin's avatar
Daniil Osokin committed
2018 2019 2020 2021
    }
    catch(...)
    {
        metrics.terminationReason = performance_metrics::TERM_EXCEPTION;
2022
        FAIL() << "Expected: PerfTestBody() doesn't throw an exception.\n  Actual: it throws...";
Daniil Osokin's avatar
Daniil Osokin committed
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
    }
}

/*****************************************************************************************\
*                          ::perf::TestBase::_declareHelper
\*****************************************************************************************/
TestBase::_declareHelper& TestBase::_declareHelper::iterations(unsigned int n)
{
    test->times.clear();
    test->times.reserve(n);
    test->nIters = std::min(n, TestBase::iterationsLimitDefault);
    test->currentIter = (unsigned int)-1;
2035
    test->metrics.clear();
Daniil Osokin's avatar
Daniil Osokin committed
2036 2037 2038 2039 2040 2041 2042 2043
    return *this;
}

TestBase::_declareHelper& TestBase::_declareHelper::time(double timeLimitSecs)
{
    test->times.clear();
    test->currentIter = (unsigned int)-1;
    test->timeLimit = (int64)(timeLimitSecs * cv::getTickFrequency());
2044
    test->metrics.clear();
Daniil Osokin's avatar
Daniil Osokin committed
2045 2046 2047 2048 2049
    return *this;
}

TestBase::_declareHelper& TestBase::_declareHelper::tbb_threads(int n)
{
2050
    cv::setNumThreads(n);
Daniil Osokin's avatar
Daniil Osokin committed
2051 2052 2053 2054 2055 2056 2057 2058 2059
    return *this;
}

TestBase::_declareHelper& TestBase::_declareHelper::runs(unsigned int runsNumber)
{
    test->runsPerIteration = runsNumber;
    return *this;
}

2060
TestBase::_declareHelper& TestBase::_declareHelper::in(cv::InputOutputArray a1, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2061 2062 2063 2064 2065 2066
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->inputData, a1, wtype);
    return *this;
}

2067
TestBase::_declareHelper& TestBase::_declareHelper::in(cv::InputOutputArray a1, cv::InputOutputArray a2, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2068 2069 2070 2071 2072 2073 2074
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->inputData, a1, wtype);
    TestBase::declareArray(test->inputData, a2, wtype);
    return *this;
}

2075
TestBase::_declareHelper& TestBase::_declareHelper::in(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2076 2077 2078 2079 2080 2081 2082 2083
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->inputData, a1, wtype);
    TestBase::declareArray(test->inputData, a2, wtype);
    TestBase::declareArray(test->inputData, a3, wtype);
    return *this;
}

2084
TestBase::_declareHelper& TestBase::_declareHelper::in(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, cv::InputOutputArray a4, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2085 2086 2087 2088 2089 2090 2091 2092 2093
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->inputData, a1, wtype);
    TestBase::declareArray(test->inputData, a2, wtype);
    TestBase::declareArray(test->inputData, a3, wtype);
    TestBase::declareArray(test->inputData, a4, wtype);
    return *this;
}

2094
TestBase::_declareHelper& TestBase::_declareHelper::out(cv::InputOutputArray a1, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2095 2096 2097 2098 2099 2100
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->outputData, a1, wtype);
    return *this;
}

2101
TestBase::_declareHelper& TestBase::_declareHelper::out(cv::InputOutputArray a1, cv::InputOutputArray a2, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2102 2103 2104 2105 2106 2107 2108
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->outputData, a1, wtype);
    TestBase::declareArray(test->outputData, a2, wtype);
    return *this;
}

2109
TestBase::_declareHelper& TestBase::_declareHelper::out(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2110 2111 2112 2113 2114 2115 2116 2117
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->outputData, a1, wtype);
    TestBase::declareArray(test->outputData, a2, wtype);
    TestBase::declareArray(test->outputData, a3, wtype);
    return *this;
}

2118
TestBase::_declareHelper& TestBase::_declareHelper::out(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, cv::InputOutputArray a4, WarmUpType wtype)
Daniil Osokin's avatar
Daniil Osokin committed
2119 2120 2121 2122 2123 2124 2125 2126 2127
{
    if (!test->times.empty()) return *this;
    TestBase::declareArray(test->outputData, a1, wtype);
    TestBase::declareArray(test->outputData, a2, wtype);
    TestBase::declareArray(test->outputData, a3, wtype);
    TestBase::declareArray(test->outputData, a4, wtype);
    return *this;
}

2128 2129 2130 2131 2132 2133
TestBase::_declareHelper& TestBase::_declareHelper::strategy(enum PERF_STRATEGY s)
{
    test->testStrategy = s;
    return *this;
}

Daniil Osokin's avatar
Daniil Osokin committed
2134 2135 2136 2137
TestBase::_declareHelper::_declareHelper(TestBase* t) : test(t)
{
}

2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
/*****************************************************************************************\
*                                  miscellaneous
\*****************************************************************************************/

namespace {
struct KeypointComparator
{
    std::vector<cv::KeyPoint>& pts_;
    comparators::KeypointGreater cmp;

    KeypointComparator(std::vector<cv::KeyPoint>& pts) : pts_(pts), cmp() {}

    bool operator()(int idx1, int idx2) const
    {
        return cmp(pts_[idx1], pts_[idx2]);
    }
Andrey Kamaev's avatar
Andrey Kamaev committed
2154 2155
private:
    const KeypointComparator& operator=(const KeypointComparator&); // quiet MSVC
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
};
}//namespace

void perf::sort(std::vector<cv::KeyPoint>& pts, cv::InputOutputArray descriptors)
{
    cv::Mat desc = descriptors.getMat();

    CV_Assert(pts.size() == (size_t)desc.rows);
    cv::AutoBuffer<int> idxs(desc.rows);

    for (int i = 0; i < desc.rows; ++i)
        idxs[i] = i;

    std::sort((int*)idxs, (int*)idxs + desc.rows, KeypointComparator(pts));

    std::vector<cv::KeyPoint> spts(pts.size());
    cv::Mat sdesc(desc.size(), desc.type());

    for(int j = 0; j < desc.rows; ++j)
    {
        spts[j] = pts[idxs[j]];
        cv::Mat row = sdesc.row(j);
        desc.row(idxs[j]).copyTo(row);
    }

    spts.swap(pts);
    sdesc.copyTo(desc);
}

2185 2186 2187 2188 2189
/*****************************************************************************************\
*                                  ::perf::GpuPerf
\*****************************************************************************************/
bool perf::GpuPerf::targetDevice()
{
2190
    return param_impl == "cuda";
2191
}
2192

Daniil Osokin's avatar
Daniil Osokin committed
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
/*****************************************************************************************\
*                                  ::perf::PrintTo
\*****************************************************************************************/
namespace perf
{

void PrintTo(const MatType& t, ::std::ostream* os)
{
    switch( CV_MAT_DEPTH((int)t) )
    {
        case CV_8U:  *os << "8U";  break;
        case CV_8S:  *os << "8S";  break;
        case CV_16U: *os << "16U"; break;
        case CV_16S: *os << "16S"; break;
        case CV_32S: *os << "32S"; break;
        case CV_32F: *os << "32F"; break;
        case CV_64F: *os << "64F"; break;
        case CV_USRTYPE1: *os << "USRTYPE1"; break;
        default: *os << "INVALID_TYPE"; break;
    }
    *os << 'C' << CV_MAT_CN((int)t);
}

} //namespace perf

/*****************************************************************************************\
*                                  ::cv::PrintTo
\*****************************************************************************************/
namespace cv {

2223 2224
void PrintTo(const String& str, ::std::ostream* os)
{
2225
    *os << "\"" << str << "\"";
2226 2227
}

Daniil Osokin's avatar
Daniil Osokin committed
2228 2229 2230 2231 2232 2233
void PrintTo(const Size& sz, ::std::ostream* os)
{
    *os << /*"Size:" << */sz.width << "x" << sz.height;
}

}  // namespace cv