File indexing completed on 2024-11-10 04:56:54

0001 /*
0002     KWin - the KDE window manager
0003     This file is part of the KDE project.
0004 
0005     SPDX-FileCopyrightText: 2023 Xaver Hugl <xaver.hugl@gmail.com>
0006 
0007     SPDX-License-Identifier: GPL-2.0-or-later
0008 */
0009 #include "glrendertimequery.h"
0010 #include "opengl/glplatform.h"
0011 
0012 namespace KWin
0013 {
0014 
0015 GLRenderTimeQuery::GLRenderTimeQuery()
0016 {
0017     if (GLPlatform::instance()->supports(GLFeature::TimerQuery)) {
0018         glGenQueries(1, &m_query);
0019     }
0020 }
0021 
0022 GLRenderTimeQuery::~GLRenderTimeQuery()
0023 {
0024     if (m_query) {
0025         glDeleteQueries(1, &m_query);
0026     }
0027 }
0028 
0029 void GLRenderTimeQuery::begin()
0030 {
0031     if (m_query) {
0032         GLint64 nanos = 0;
0033         glGetInteger64v(GL_TIMESTAMP, &nanos);
0034         m_cpuStart = std::chrono::nanoseconds(nanos);
0035     } else {
0036         m_cpuStart = std::chrono::steady_clock::now().time_since_epoch();
0037     }
0038 }
0039 
0040 void GLRenderTimeQuery::end()
0041 {
0042     if (m_query) {
0043         glQueryCounter(m_query, GL_TIMESTAMP);
0044     } else {
0045         m_cpuEnd = std::chrono::steady_clock::now().time_since_epoch();
0046     }
0047     m_hasResult = true;
0048 }
0049 
0050 std::chrono::nanoseconds GLRenderTimeQuery::result()
0051 {
0052     if (!m_hasResult) {
0053         return std::chrono::nanoseconds::zero();
0054     }
0055     m_hasResult = false;
0056     if (m_query) {
0057         uint64_t nanos = 0;
0058         glGetQueryObjectui64v(m_query, GL_QUERY_RESULT, &nanos);
0059         if (nanos == 0) {
0060             return std::chrono::nanoseconds::zero();
0061         }
0062         return std::chrono::nanoseconds(nanos) - m_cpuStart;
0063     } else {
0064         return m_cpuEnd - m_cpuStart;
0065     }
0066 }
0067 
0068 }