kyuunex
kyuunex

Reputation: 11

Run C++ loop for a specific time

I'm getting started with C++ and I decided to do some random coding just for practice. So I was thinking of making a simple benchmarking program, here's how far I have gotten:

#include <iostream>
#include <ctime>

using namespace std;

int main(){
    cout << "press any key to start benchmarking" << endl;
    cin.get();

    int pref_scorecounter = 0;
    time_t pref_timestart = time(0);
    do {
        pref_scorecounter++;
        time_t pref_timefinish = time(0);
        int pref_timeduration = pref_timefinish - pref_timestart;
    } while ( pref_timeduration < 5 );
    cout << "Score: " << pref_scorecounter;
    cin.get();
}

The way it works is that it shows how much times has the loop happened in 5 seconds. But I get this error:

error: 'pref_timeduration' was not declared in this scope

Any ideas why the variable defined in a loop doesn't work? Also why does this program not run at 100% cpu?

This project was ported from a PHP project I made a while ago and that PHP code works 100%, I tested with different servers and etc.

<?php
$pref_scorecounter = 0;
$pref_timestart = microtime(true); 
do {
    $pref_scorecounter++;
    $pref_timefinish = microtime(true);
    $pref_timeduration = $pref_timefinish - $pref_timestart;
} while($pref_timeduration < 5);
echo "Score: " . $pref_scorecounter;
?>

I can add some complex calculations later though...

Upvotes: 0

Views: 1644

Answers (4)

dspfnder
dspfnder

Reputation: 1123

In a do-while statement, the body is executed before the condition is evaluated. But for what's in the body to work properly, including the declaration of pref_timeduration, the condition must be true. Bjarne Stroustrup recommends against the use of do-while loops.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

The languages have different scoping rules.

In C++ the scope ends on closing bracket. If you want to use the variable in the condition, its definition has to be outside of loop scope.

Upvotes: 1

Pooja Nilangekar
Pooja Nilangekar

Reputation: 1469

Your problem is simple, it is related to the scope of the variable pref_timeduration. You've declared the variable inside the loop while you're trying to access it outside. Initialize the variable outside the do {} while() loop and update it inside the loop.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234655

pref_timeduration is defined within the scope block of the while loop.

It therefore cannot be used in the loop exit test: while( pref_timeduration < 5) is invalid and your compiler is telling you this.

One fix is to declare pref_timeduration just before the do. You can put an extra pair of braces around the whole thing if you're concerned about leaking the scope of pref_timeduration to other parts of the function.

Upvotes: 0

Related Questions