summaryrefslogtreecommitdiff
path: root/zen/perf.h
blob: 8760ef0b8190a3c2f6f39d2228d8fb472663765f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// **************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: http://www.gnu.org/licenses/gpl.html       *
// * Copyright (C) ZenJu (zenju AT gmx DOT de) - All Rights Reserved        *
// **************************************************************************

#ifndef DEBUG_PERF_HEADER
#define DEBUG_PERF_HEADER

#include "deprecate.h"
#include "tick_count.h"

#ifdef FFS_WIN
#include <sstream>
#else
#include <iostream>
#endif

//############# two macros for quick performance measurements ###############
#define PERF_START zen::PerfTimer perfTest;
#define PERF_STOP  perfTest.showResult();
//###########################################################################

namespace zen
{
class PerfTimer
{
public:
    class TimerError {};

    ZEN_DEPRECATE
    PerfTimer() : ticksPerSec_(ticksPerSec()), startTime(), resultShown(false)
    {
        //std::clock() - "counts CPU time in C and wall time in VC++" - WTF!???
#ifdef FFS_WIN
        if (::SetThreadAffinityMask(::GetCurrentThread(), 1) == 0) throw TimerError(); //"should not be required unless there are bugs in BIOS or HAL" - msdn, QueryPerformanceCounter
#endif
        startTime = getTicks();
        if (ticksPerSec_ == 0 || !startTime.isValid())
            throw TimerError();
    }

    ~PerfTimer() { if (!resultShown) showResult(); }

    void showResult()
    {
        const TickVal now = getTicks();
        if (!now.isValid())
            throw TimerError();

        const auto delta = static_cast<long>(1000.0 * (now - startTime) / ticksPerSec_);
#ifdef FFS_WIN
        std::ostringstream ss;
        ss << delta << " ms";
        ::MessageBoxA(nullptr, ss.str().c_str(), "Timer", 0);
#else
        std::clog << "Perf: duration: " << delta << " ms\n";
#endif
        resultShown = true;

        startTime = getTicks(); //don't include call to MessageBox()!
        if (!startTime.isValid())
            throw TimerError();
    }

private:
    const std::int64_t ticksPerSec_;
    TickVal startTime;
    bool resultShown;
};
}

#endif //DEBUG_PERF_HEADER
bgstack15