cpustat.cpp 10.4 KB
Newer Older
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
/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
**
**  SysStat is a Qt-based interface to system statistics
**
**  Authors:
**       Copyright (c) 2009 - 2012 Kuzma Shapran <Kuzma.Shapran@gmail.com>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library;
**  if not, write to the Free Software Foundation, Inc.,
**  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
** END_COMMON_COPYRIGHT_HEADER */


#include <unistd.h>

#include "cpustat.h"
#include "cpustat_p.h"


namespace SysStat {

CpuStatPrivate::CpuStatPrivate(CpuStat *parent)
    : BaseStatPrivate(parent)
    , mMonitoring(CpuStat::LoadAndFrequency)
{
    mSource = defaultSource();

    connect(mTimer, SIGNAL(timeout()), SLOT(timeout()));

    mUserHz = sysconf(_SC_CLK_TCK);

    updateSources();
}

void CpuStatPrivate::addSource(const QString &source)
{
    bool ok;

52
    uint min = readAllFile(qPrintable(QString::fromLatin1("/sys/devices/system/cpu/%1/cpufreq/scaling_min_freq").arg(source))).toUInt(&ok);
53 54
    if (ok)
    {
55
        uint max = readAllFile(qPrintable(QString::fromLatin1("/sys/devices/system/cpu/%1/cpufreq/scaling_max_freq").arg(source))).toUInt(&ok);
56 57 58 59 60 61 62 63 64
        if (ok)
            mBounds[source] = qMakePair(min, max);
    }
}

void CpuStatPrivate::updateSources()
{
    mSources.clear();

65
    const QStringList rows = readAllFile("/proc/stat").split(QLatin1Char('\n'), QString::SkipEmptyParts);
66
    for (const QString &row : rows)
67
    {
68
        QStringList tokens = row.split(QLatin1Char(' '), QString::SkipEmptyParts);
69
        if( (tokens.size() < 5)
70
        || (!tokens[0].startsWith(QLatin1String("cpu"))) )
71 72 73 74 75 76 77 78 79
            continue;

        mSources.append(tokens[0]);
    }

    mBounds.clear();

    bool ok;

80
    const QStringList ranges = readAllFile("/sys/devices/system/cpu/online").split(QLatin1Char(','), QString::SkipEmptyParts);
81
    for (const QString &range : ranges)
82
    {
83
        int dash = range.indexOf(QLatin1Char('-'));
84 85
        if (dash != -1)
        {
86
            uint min = range.leftRef(dash).toUInt(&ok);
87 88
            if (ok)
            {
89
                uint max = range.midRef(dash + 1).toUInt(&ok);
90 91
                if (ok)
                    for (uint number = min; number <= max; ++number)
92
                        addSource(QString::fromLatin1("cpu%1").arg(number));
93 94 95 96 97 98
            }
        }
        else
        {
            uint number = range.toUInt(&ok);
            if (ok)
99
                addSource(QString::fromLatin1("cpu%1").arg(number));
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        }
    }
}

CpuStatPrivate::~CpuStatPrivate()
{
}

void CpuStatPrivate::intervalChanged()
{
    recalculateMinMax();
}

void CpuStatPrivate::sourceChanged()
{
    recalculateMinMax();
}

void CpuStatPrivate::recalculateMinMax()
{
    int cores = 1;
121
    if (mSource == QLatin1String("cpu"))
122 123 124 125 126 127 128 129 130 131 132
        cores = mSources.size() - 1;

    mIntervalMin = static_cast<float>(mTimer->interval()) / 1000 * static_cast<float>(mUserHz) * static_cast<float>(cores) / 1.25; // -25%
    mIntervalMax = static_cast<float>(mTimer->interval()) / 1000 * static_cast<float>(mUserHz) * static_cast<float>(cores) * 1.25; // +25%
}

void CpuStatPrivate::timeout()
{
    if ( (mMonitoring == CpuStat::LoadOnly)
      || (mMonitoring == CpuStat::LoadAndFrequency) )
    {
133
        const QStringList rows = readAllFile("/proc/stat").split(QLatin1Char('\n'), QString::SkipEmptyParts);
134
        for (const QString &row : rows)
135
        {
136
            if (!row.startsWith(QLatin1String("cpu")))
137 138
                continue;

139
            if (row.startsWith(mSource + QLatin1Char(' ')))
140
            {
141
                QStringList tokens = row.split(QLatin1Char(' '), QString::SkipEmptyParts);
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
                if (tokens.size() < 5)
                    continue;

                Values current;
                current.user   = tokens[1].toULongLong();
                current.nice   = tokens[2].toULongLong();
                current.system = tokens[3].toULongLong();
                current.idle   = tokens[4].toULongLong();
                current.other  = 0;
                int m = tokens.size();
                for (int i = 5; i < m; ++i)
                    current.other += tokens[i].toULongLong();
                current.sum();

                float sumDelta = static_cast<float>(current.total - mPrevious.total);

                if ((mPrevious.total != 0) && ((sumDelta < mIntervalMin) || (sumDelta > mIntervalMax)))
                {
                    if (mMonitoring == CpuStat::LoadAndFrequency)
                        emit update(0.0, 0.0, 0.0, 0.0, 0.0, 0);
                    else
                        emit update(0.0, 0.0, 0.0, 0.0);

                    mPrevious.clear(); // make sure it won't keep crazy values.
                }
                else
                {
                    if (mMonitoring == CpuStat::LoadAndFrequency)
                    {
                        float freqRate = 1.0;
                        uint freq = 0;

                        bool ok;

176
                        if (mSource == QLatin1String("cpu"))
177 178 179 180 181 182
                        {
                            uint count = 0;
                            freqRate = 0.0;

                            for (Bounds::ConstIterator I = mBounds.constBegin(); I != mBounds.constEnd(); ++I)
                            {
183
                                uint thisFreq = readAllFile(qPrintable(QString::fromLatin1("/sys/devices/system/cpu/%1/cpufreq/scaling_cur_freq").arg(I.key()))).toUInt(&ok);
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

                                if (ok)
                                {
                                    freq += thisFreq;
                                    freqRate += static_cast<float>(thisFreq) / static_cast<float>(I.value().second);
                                    ++count;
                                }
                            }
                            if (!count)
                                freqRate = 1.0;
                            else
                            {
                                freq /= count;
                                freqRate /= count;
                            }
                        }
                        else
                        {
202
                            freq = readAllFile(qPrintable(QString::fromLatin1("/sys/devices/system/cpu/%1/cpufreq/scaling_cur_freq").arg(mSource))).toUInt(&ok);
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 237 238

                            if (ok)
                            {
                                Bounds::ConstIterator I = mBounds.constFind(mSource);
                                if (I != mBounds.constEnd())
                                    freqRate = static_cast<float>(freq) / static_cast<float>(I.value().second);
                            }
                        }

                        emit update(
                            static_cast<float>(current.user   - mPrevious.user  ) / sumDelta,
                            static_cast<float>(current.nice   - mPrevious.nice  ) / sumDelta,
                            static_cast<float>(current.system - mPrevious.system) / sumDelta,
                            static_cast<float>(current.other  - mPrevious.other ) / sumDelta,
                            freqRate,
                            freq);
                    }
                    else
                    {
                        emit update(
                            static_cast<float>(current.user   - mPrevious.user  ) / sumDelta,
                            static_cast<float>(current.nice   - mPrevious.nice  ) / sumDelta,
                            static_cast<float>(current.system - mPrevious.system) / sumDelta,
                            static_cast<float>(current.other  - mPrevious.other ) / sumDelta);
                    }

                    mPrevious = current;
                }
            }
        }
    }
    else
    {
        bool ok;
        uint freq = 0;

239
        if (mSource == QLatin1String("cpu"))
240 241 242 243 244
        {
            uint count = 0;

            for (Bounds::ConstIterator I = mBounds.constBegin(); I != mBounds.constEnd(); ++I)
            {
245
                uint thisFreq = readAllFile(qPrintable(QString::fromLatin1("/sys/devices/system/cpu/%1/cpufreq/scaling_cur_freq").arg(I.key()))).toUInt(&ok);
246 247 248 249 250 251 252 253 254 255 256 257 258 259

                if (ok)
                {
                    freq += thisFreq;
                    ++count;
                }
            }
            if (count)
            {
                freq /= count;
            }
        }
        else
        {
260
            freq = readAllFile(qPrintable(QString::fromLatin1("/sys/devices/system/cpu/%1/cpufreq/scaling_cur_freq").arg(mSource))).toUInt(&ok);
261 262 263 264 265 266 267
        }
        emit update(freq);
    }
}

QString CpuStatPrivate::defaultSource()
{
268
    return QLatin1String("cpu");
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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
}

CpuStatPrivate::Values::Values()
    : user(0)
    , nice(0)
    , system(0)
    , idle(0)
    , other(0)
    , total(0)
{
}

void CpuStatPrivate::Values::sum()
{
    total = user + nice + system + idle + other;
}

void CpuStatPrivate::Values::clear()
{
    total = user = nice = system = idle = other = 0;
}

CpuStat::Monitoring CpuStatPrivate::monitoring() const
{
    return mMonitoring;
}

void CpuStatPrivate::setMonitoring(CpuStat::Monitoring value)
{
    mPrevious.clear();
    mMonitoring = value;
}

CpuStat::CpuStat(QObject *parent)
    : BaseStat(parent)
{
    impl = new CpuStatPrivate(this);
    baseimpl = impl;

    connect(impl, SIGNAL(update(float,float,float,float,float,uint)), this, SIGNAL(update(float,float,float,float,float,uint)));
    connect(impl, SIGNAL(update(float,float,float,float)), this, SIGNAL(update(float,float,float,float)));
    connect(impl, SIGNAL(update(uint)), this, SIGNAL(update(uint)));
}

CpuStat::~CpuStat()
{
}

void CpuStat::updateSources()
{
    dynamic_cast<CpuStatPrivate*>(impl)->updateSources();
}

CpuStat::Monitoring CpuStat::monitoring() const
{
    return impl->monitoring();
}

void CpuStat::setMonitoring(CpuStat::Monitoring value)
{
    if (impl->monitoring() != value)
    {
        impl->setMonitoring(value);
        emit monitoringChanged(value);
    }
}

}