Search code examples
c++qtqt5qthread

How can I reduce the CPU usage of my application?


My application involves taking backup of certain sqlite database as set by user. This backup is based on certain conditions. So in order to do that I am using a worker object(running on QThread) do check if the conditions match. If the condition matches I take the backup. My problem is, i have checked the task manager and my application always uses a minimum of 25%(since the thread is running). If i disable the automatic backup, it is back to normal. Am I doing anything wrong or is this normal ? Please can anyone point me how to keep the cpu usage low? Below is my code for the automatic backup thread.

void Automatic_Backup_Logic::Thread_Run()
{
    QSettings settings(ORGANISATION, APPLICATION_NAME);
    while(!m_Stop){
        // First check the backup type
        int backup_type = settings.value(BACKUP_TYPE).toInt();
        QTime BackupTime = qvariant_cast<QTime>(settings.value(BACKUP_TIME));

        // Check for backup time; if it's in range only then do backup
        if(!Check_Backup_Time(BackupTime)){
            continue;
        }

        switch (backup_type)
        {
            case BACKUP_TYPE_MANUAL:
            // do nothing here
                continue;

            case BACKUP_TYPE_DAILY:
                Backup_Daily();
                break;

            case BACKUP_TYPE_WEEKLY:
                Backup_Weekly();
                break;

            case BACKUP_TYPE_MONTHLY:
                Backup_Monthly();
                break;

            case BACKUP_TYPE_YEARLY:
                Backup_Yearly();
                break;

            default:
                break;
        }

        // Wait for the current backup minute to pass by to avoid multiple copies
        QTime t1 = qvariant_cast<QTime> (settings.value(BACKUP_TIME));
        while(t1.minute()==QTime::currentTime().minute()){
            if(m_Stop)
                return;
            QCoreApplication::processEvents();
        }
    }
}

PS: I am running this thread by standard Qt Procedure that is creating a worker thread and using moveToThread() function


Solution

  • As suggested in comments, I put delay in my thread now everything is working as expected. Thank you all

    Edited Code

        // Check for backup time; if it's in range only then do backup
        while(!Check_Backup_Time(BackupTime) && !m_Stop){
            QThread::sleep(1);
            BackupTime = qvariant_cast<QTime>(settings.value(BACKUP_TIME));
        }