summaryrefslogtreecommitdiff
path: root/tests/sdcard/stopwatch.cpp
blob: 77768d69c08b99d96dc030b0bd5be553469b9f20 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/*
 * Copyright (C) 2009 The Android Open Source Project
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */


#include <malloc.h>
#include <stdio.h>
#include <time.h>
#include "stopwatch.h"
#include <math.h>

#define SNPRINTF_OR_RETURN(str, size, format, ...) {                    \
        int len = snprintf((str), (size), (format), ## __VA_ARGS__);    \
        if (len < 0) return;                                            \
        if (len > static_cast<int>(size)) {                             \
            fprintf(stderr, "Not enough space\n");                      \
            return;                                                     \
        } else {                                                        \
            (size) -= len; (str) += len;                                \
        }                                                               \
    }

namespace {
const bool kVerbose = false;
bool printRaw = false;
}

namespace android_test {

StopWatch::StopWatch(const char *name, size_t capacity)
    : mName(strdup(name)), mNum(0), mData(NULL), mDataLen(0), mCapacity(capacity * 2),
      mSizeKbytes(0), mAlreadyPrinted(false), mPrintRaw(false),
      mDuration(0.0), mDeviation(0.0),
      mMinDuration(0.0), mMinIdx(0),
      mMaxDuration(0.0), mMaxIdx(0),
      mDeltas(NULL), mUsed(false)
{
    mStart.tv_sec = 0;
    mStart.tv_nsec = 0;
    mData = (Measurement *) malloc(mCapacity * sizeof(Measurement));
}

StopWatch::~StopWatch()
{
    if (mUsed && !mAlreadyPrinted)
    {
        fprintf(stderr, "Discarding data for %s\n", mName);
    }
    free(mData);
    free(mName);
    delete [] mDeltas;
}

void StopWatch::start()
{
    checkCapacity();
    clock_gettime(CLOCK_MONOTONIC, &mData[mDataLen].mTime);
    mData[mDataLen].mIsStart = true;
    if (!mUsed)
    {
        mStart = mData[mDataLen].mTime; // mDataLen should be 0
        mUsed = true;
    }
    ++mNum;
    ++mDataLen;
}

void StopWatch::stop()
{
    checkCapacity();
    clock_gettime(CLOCK_MONOTONIC, &mData[mDataLen].mTime);
    mData[mDataLen].mIsStart = false;
    ++mDataLen;
}

void StopWatch::setPrintRawMode(bool raw)
{
    printRaw = raw;
}


void StopWatch::sprint(char **str, size_t *size)
{
    if (kVerbose) fprintf(stderr, "printing\n");
    mAlreadyPrinted = true;
    if (0 == mDataLen)
    {
        return;
    }
    if (mDataLen > 0 && mData[mDataLen - 1].mIsStart)
    {
        stop();
    }
    if (kVerbose) SNPRINTF_OR_RETURN(*str, *size, "# Got %d samples for %s\n", mDataLen, mName);
    processSamples();

    SNPRINTF_OR_RETURN(*str, *size, "# StopWatch %s total/cumulative duration %f Samples: %d\n",
                       mName, mDuration, mNum);
    printThroughput(str, size);
    printAverageMinMax(str, size);

    if (printRaw)
    {
        // print comment header and summary values.

        SNPRINTF_OR_RETURN(*str, *size, "# Name Iterations  Duration Min MinIdx Max MaxIdx SizeKbytes\n");
        SNPRINTF_OR_RETURN(*str, *size, "%s %d %f %f %d %f %d %d\n", mName, mNum, mDuration,
                           mMinDuration, mMinIdx, mMaxDuration, mMaxIdx, mSizeKbytes);
        // print each duration sample
        for (size_t i = 0; i < mDataLen / 2; ++i)
        {
            long second = mData[i * 2].mTime.tv_sec - mStart.tv_sec;
            long nano = mData[i * 2].mTime.tv_nsec - mStart.tv_nsec;

            SNPRINTF_OR_RETURN(*str, *size, "%f %f\n", double(second) + double(nano) / 1.0e9, mDeltas[i]);
        }
    }

}

// Normally we should have enough capacity but if we have to
// reallocate the measurement buffer (e.g start and stop called more
// than once in an iteration) we let the user know. She should provide
// a capacity when building the StopWatch.
void StopWatch::checkCapacity()
{
    if (mDataLen >= mCapacity)
    {
        mCapacity *= 2;
        fprintf(stderr, "# Increased capacity to %d for %s. Measurement affected.\n",
                mCapacity, mName);
        mData = (Measurement *)realloc(mData, mCapacity * sizeof(Measurement));
    }
}


// Go over all the samples and compute the diffs between a start and
// stop pair. The diff is accumulated in mDuration and inserted in
// mDeltas.
// The min and max values for a diff are also tracked.
void StopWatch::processSamples()
{
    if (kVerbose) fprintf(stderr, "processing samples\n");
    size_t n = mDataLen / 2;
    mDeltas= new double[n];
    for (size_t i = 0; i < mDataLen; i += 2)   // even: start  odd: stop
    {
        long second = mData[i + 1].mTime.tv_sec - mData[i].mTime.tv_sec;
        long nano = mData[i + 1].mTime.tv_nsec - mData[i].mTime.tv_nsec;

        mDeltas[i / 2] = double(second) + double(nano) / 1.0e9;
    }

    for (size_t i = 0; i < n; ++i)
    {
        if (0 == i)
        {
            mMinDuration = mMaxDuration = mDeltas[i];
        }
        else
        {
            if (mMaxDuration < mDeltas[i])
            {
                mMaxDuration = mDeltas[i];
                mMaxIdx = i;
            }
            if (mMinDuration > mDeltas[i])
            {
                mMinDuration = mDeltas[i];
                mMinIdx = i;
            }
        }
        mDuration += mDeltas[i];
    }
    double avgDuration = mDuration / n;
    double diffSQ = 0.0;
    for (size_t i = 0; i < n; ++i)
    {
      diffSQ += pow((mDeltas[i] - avgDuration), 2.0);
    }
    mDeviation = sqrt(diffSQ / n);
}


double StopWatch::timespecToDouble(const struct timespec& time)
{
    double val = double(time.tv_nsec) / 1.0e9 + double(time.tv_sec);
    return val < 0.0 ? -val : val;  // sometimes 0.00 is -0.00
}


// If we have only 2 values, don't bother printing anything.
void StopWatch::printAverageMinMax(char **str, size_t *size)
{
    if (mDataLen > 2) // if there is only one sample, avg, min, max are trivial.
    {
        SNPRINTF_OR_RETURN(*str, *size, "# Average %s duration %f s/op\n", mName, mDuration / mNum);
        SNPRINTF_OR_RETURN(*str, *size, "# Standard deviation %s duration %f \n", mName, mDeviation);
        SNPRINTF_OR_RETURN(*str, *size, "# Min %s duration %f [%d]\n", mName, mMinDuration, mMinIdx);
        SNPRINTF_OR_RETURN(*str, *size, "# Max %s duration %f [%d]\n", mName, mMaxDuration, mMaxIdx);
    }
}

void StopWatch::printThroughput(char **str, size_t *size)
{
    if (0 != mSizeKbytes)
    {
        SNPRINTF_OR_RETURN(*str, *size, "# Size: %d Kbytes  Total: %d\n", mSizeKbytes, mNum);
        SNPRINTF_OR_RETURN(*str, *size, "# Speed %f Kbyte/s\n", double(mSizeKbytes) * mNum / mDuration);
    }
}
}  // namespace android_test