Metronome: Difference between revisions

Content added Content deleted
(Added XPL0 example.)
(New post.)
Line 265: Line 265:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|C++}}==
This example has a timing loop to ensure that its timing is reliable in the long term.
<syntaxhighlight lang="c++">
#include <chrono>
#include <cstdint>
#include <iostream>
#include <thread>

class Metronome {
public:
Metronome(const double& aBeats_per_minute, const int32_t& aMeasure, const int32_t aDuration_in_minutes)
: beats_per_minute(aBeats_per_minute), measure(aMeasure), duration(aDuration_in_minutes) {
counter = 0;
}

void start() {
while ( counter < duration * beats_per_minute ) {
start_time = std::chrono::system_clock::now();

std::this_thread::sleep_until(time_to_awake());
counter++;
if ( counter % measure != 0 ) {
std::cout << "Tick " << std::flush;
} else {
std::cout << "Tock" << std::endl;
}
}
}

private:
std::chrono::system_clock::time_point time_to_awake() const {
return start_time + std::chrono::seconds(1);
}

std::chrono::system_clock::time_point start_time;
int32_t counter;

const double beats_per_minute;
const int32_t measure, duration;
};

int main() {
Metronome metronome(60, 4, 1);
metronome.start();
}
</syntaxhighlight>
{{ out }}
<pre>
Tick Tick Tick Tock
Tick Tick Tick Tock
Tick Tick
// continues for the requested duration
</pre>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==