Skip to content

Instantly share code, notes, and snippets.

@colrichie
Last active May 8, 2025 17:24
Show Gist options
  • Save colrichie/019fa2b75b9842d2c06cbfc51f4115e6 to your computer and use it in GitHub Desktop.
Save colrichie/019fa2b75b9842d2c06cbfc51f4115e6 to your computer and use it in GitHub Desktop.
//////////////////////////////////////////////////////////////////////
//
// A Sample Program of waitill() for C++17
//
// You can make a little simpler interval loop by using the
// "Punctual::waitill()" method than by using the
// "std::this_thread::sleep_until()" function simply.
//
// The following C++ program prints a message every 0.5 ms accurately.
//
// THIS SAMPLE IS DEDICATED TO PUNCTUAL PROGRAMMERS IN THE WORLD!
//
// Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2025-05-09
//
//////////////////////////////////////////////////////////////////////
#include <chrono> // for std::chrono
#include <ctime> // for std::timespec
#include <thread> // for std::this_thread::sleep_until
#include <iostream>
class Punctual {
private:
using hr_clk = std::chrono::high_resolution_clock;
using time_point = hr_clk::time_point;
using duration = hr_clk::duration;
time_point wt_epoch;
public:
Punctual() {wt_epoch = hr_clk::now();}
time_point now() const {return hr_clk::now(); }
time_point get_epoch() const {return wt_epoch; }
time_point redef_epoch() {wt_epoch = hr_clk::now();
return wt_epoch; }
bool waitill(double sec_to_ret) {
using namespace std::chrono;
auto duration = std::chrono::duration<double>(sec_to_ret);
auto due = wt_epoch + duration_cast<hr_clk::duration>(duration);
std::this_thread::sleep_until(due);
return true;
}
bool waitill(duration duration_to_ret) {
auto due = wt_epoch + duration_to_ret;
std::this_thread::sleep_until(due);
return true;
}
bool waitill(std::timespec& ts) {
auto due = wt_epoch + std::chrono::seconds( ts.tv_sec )
+ std::chrono::nanoseconds(ts.tv_nsec);
std::this_thread::sleep_until(due);
return true;
}
};
int main() {
Punctual punc;
std::cout << "Set the epoch.\n";
for (double t=0.5; t<=5.0; t+=0.5) {
punc.waitill(t);
std::cout << t << " second(s) have past." << std::endl;
}
return 0;
}
//////////////////////////////////////////////////////////////////////
//
// A Sample Program of waitill() for Golang
//
// You can make a more accurate interval loop by using the "Punctual.Waitill()"
// method than by using the "time.Sleep()" function simply.
//
// The following Golang program can make the 0.5 ms interval printing
// more accurate than typical sample programs.
//
// THIS SAMPLE IS DEDICATED TO PUNCTUAL PROGRAMMERS IN THE WORLD!
//
// Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2025-05-09
//
//////////////////////////////////////////////////////////////////////
package main
import (
"fmt"
"time"
)
type Punctual struct {wt_epoch time.Time}
func NewPunctual() *Punctual {return &Punctual{
wt_epoch: time.Now()}}
func (p *Punctual) Now() time.Time {return time.Now() }
func (p *Punctual) RedefEpoch() time.Time {p.wt_epoch=time.Now()
return p.wt_epoch }
func (p *Punctual) GetEpoch() time.Time {return p.wt_epoch }
func (p *Punctual) Waitill(secToRet float64) bool {
targetTime := p.wt_epoch.Add(time.Duration(secToRet * float64(time.Second)))
now := time.Now()
if targetTime.After(now) {
duration := targetTime.Sub(now)
time.Sleep(duration)
}
return true
}
func main() {
p := NewPunctual()
fmt.Println("Set the epoch.")
for t := 0.5; t <= 5.0; t += 0.5 {
p.Waitill(t)
fmt.Printf("%.1f second(s) have past.\n", t)
}
}
//////////////////////////////////////////////////////////////////////
//
// A Sample Program of waitill() for JavaScript
//
// You can make a more accurate interval loop by using the
// "Punctual.prototype.waitill()" method than by using the setTimeout()
// function simply.
//
// The following JavaScript program can make the 0.5 ms interval printing
// more accurate than typical sample programs.
//
// THIS SAMPLE IS DEDICATED TO PUNCTUAL PROGRAMMERS IN THE WORLD!
//
// Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2025-05-08
//
//////////////////////////////////////////////////////////////////////
class Punctual {
#wt_epoch;
constructor() {this.#wt_epoch = new Date(); }
now() {return new Date(); }
get_epoch() {return new Date(this.#wt_epoch.getTime());}
redef_epoch() {this.#wt_epoch = new Date();
return new Date(this.#wt_epoch.getTime());}
async waitill(sec_since_epoch) {
if (typeof(sec_since_epoch)!=='number' || isNaN(sec_since_epoch)) {
throw new Error('"sec_since_epoch" argument must be a valid number');
}
const dt = new Date() - this.#wt_epoch;
const msec = sec_since_epoch*1000 - dt;
if (msec <= 0 ) {return;}
await new Promise(res => setTimeout(res,msec));
return true;
}
}
(async () => {
const punc = new Punctual();
console.log('Set the epoch.');
for (let t=0.5; t<=5.0; t+=0.5) {
await punc.waitill(t);
console.log(t+' second(s) have past.');
}
})();
#!/bin/sh
exec php -q "$0" "$@"
<?php
######################################################################
#
# A Sample Program of waitill() for PHP
#
# You can make a little simpler interval loop by using the
# "Punctual::waitill()" function than by using the time_sleep_until()
# function simply.
#
# The following PHP script prints a message every 0.5 ms accurately.
#
# THIS SAMPLE IS DEDICATED TO PUNCTUAL PROGRAMMERS IN THE WORLD!
#
# Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2025-05-09
#
######################################################################
class Punctual
{
private float $wt_epoch;
public function __construct()
{
$this->wt_epoch = microtime(true);
}
public function now(): float
{
return microtime(true);
}
public function get_epoch(): float
{
return $this->wt_epoch;
}
public function redef_epoch(): float
{
$this->wt_epoch = microtime(true);
return $this->wt_epoch;
}
public function waitill(float $sec_to_ret): bool
{
$time_to_ret = $this->wt_epoch + $sec_to_ret;
$old_err_lv = error_reporting(E_ERROR | E_PARSE);
time_sleep_until($time_to_ret);
error_reporting($old_err_lv);
return true;
}
}
$punc = new Punctual();
echo "Set the epoch.\n";
for ($t=0.5; $t<=5.0; $t+=0.5) {
$punc->waitill($t);
printf("%.1f second(s) have past.\n", $t);
}
?>
#!/usr/bin/env python3
# ####################################################################
#
# A Sample Program of waitill() for Python3
#
# You can make a more accurate interval loop by using the "Punctual.waitill()"
# function than by using the time.sleep() function simply.
#
# The following Python script can make the 0.5 ms interval printing
# more accurate than typical sample programs.
#
# THIS SAMPLE IS DEDICATED TO PUNCTUAL PROGRAMMERS IN THE WORLD!
#
# Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2025-05-08
#
# ####################################################################
import datetime
import time
class Punctual:
_wt_epoch = 0
def __init__(self):
self._wt_epoch = datetime.datetime.now()
return
def now(self):
return datetime.datetime.now()
def get_epoch(self):
return self._wt_epoch.replace(minute=0)
def redef_epoch(self):
self._wt_epoch = datetime.datetime.now()
return self._wt_epoch.replace(minute=0)
def waitill(self, sec_since_epoch):
try:
if not isinstance(sec_since_epoch, (int, float)):
raise TypeError(f'"sec_since_epoch" must be int or float')
dt = datetime.datetime.now() - self._wt_epoch
sec = sec_since_epoch - dt.total_seconds()
if sec > 0:
time.sleep(sec)
return True
except (ValueError, TypeError):
return False
punc = Punctual()
print("Set the epoch.")
for i in range(10):
t = (i+1) * 0.5
punc.waitill(t)
print("{:03.1f} second(s) have past.".format(t))
#!/usr/bin/env ruby
######################################################################
#
# A Sample Program of waitill() for Ruby
#
# You can make a more accurate interval loop by using the "Punctual.waitill()"
# function than by using the time.sleep() function simply.
#
# The following ruby script can make the 0.5 ms interval printing
# more accurate than typical sample programs.
#
# THIS SAMPLE IS DEDICATED TO PUNCTUAL PROGRAMMERS IN THE WORLD!
#
# Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2025-05-08
#
######################################################################
class Punctual
def initialize
@wt_epoch = Time.now
end
def now
Time.now
end
def get_epoch
@wt_epoch.dup
end
def redef_epoch
@wt_epoch = Time.now
@wt_epoch.dup
end
def waitill(sec_to_ret)
dt = Time.now - @wt_epoch
sec = sec_to_ret - dt
sleep(sec) if sec > 0
true
end
end
punc = Punctual.new
puts "Set the epoch."
0.5.step(5.0, 0.5) do |t|
punc.waitill(t)
printf("%.1f second(s) have past.\n",t)
end
//////////////////////////////////////////////////////////////////////
//
// A Sample Program of waitill() for Arduino
//
// You can make a more accurate loop by using the "waitill()" function
// than by using the delay() function simply.
//
// The following Arduino sketch can make the 0.5 ms LED blinking more
// accurate than typical sample programs.
//
// THIS SAMPLE IS DEDICATED TO PUNCTUAL PROGRAMMERS IN THE WORLD!
//
// Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2025-05-08
//
//////////////////////////////////////////////////////////////////////
bool waitill(unsigned long millisec_to_ret);
unsigned long WT_EPOCH; // To set the reference time (epoch time)
unsigned long t; // To set the milliseconds after the WT_EPOCH
// (It is for the argment for waitill())
void setup() {
pinMode(13,OUTPUT); // LED pin
WT_EPOCH = millis();
t = 0;
}
void loop() {
digitalWrite(13,HIGH);
t += 500; // Set the next end time for the waitill(),
waitill(t); // then call it.
digitalWrite(13,LOW );
t += 500; // Set the next end time for the waitill(),
waitill(t); // then call it.
}
bool waitill(unsigned long millisec_to_ret) {
unsigned long dt;
dt = millis() - WT_EPOCH;
if (millisec_to_ret > dt) {delay(millisec_to_ret-dt);}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment