以精确的时间运行子程序,perl精度为0.1s

kob*_*ame 3 perl

需要每5秒运行一个子程序,但需要在系统时钟标记处测量.所以,需要开始于0,5,10,15 .... 45,50%,55其次,它每分钟(确切地,与0.1秒precistion).

就像是:

for(;;) {
    do_sleep(); #time need to sleep to the next 5 second mark
    run_this();
}
Run Code Online (Sandbox Code Playgroud)

所述run_this子可快可慢(其0.2之间运行时- 120秒).当它运行超过5秒时 - 无论其运行时间如何,下一次运行必须精确到5秒.

例如,当 run_this

  • 结束于11:11:12.3需要等待2.7秒到下一次运行11:11:15
  • 当以11:11:59.2结束时,需要在11:12:00等待0.8秒到下一个,依此类推......

问题是:如何编写do_sleep?

jm6*_*666 5

对于0.1s精度,您需要使用Time :: HiRes模块.就像是:

#!/usr/bin/perl
use 5.014;
use warnings;
use Time::HiRes qw(tv_interval usleep gettimeofday);

for(;;) {
    do_sleep();
    run_this();
}

sub do_sleep {
    my $t = [gettimeofday];
    my $next = (int($t->[0]/5) + 1) * 5;
    my $delta = tv_interval ($t, [$next, 0]);
    usleep($delta * 1_000_000);
    return;
}

sub run_this {
    my $t = [gettimeofday];
    printf "Start is at: %s.%s\n",
        scalar localtime  $t->[0],
        $t->[1];
    usleep( rand 10_000_000 );  #simulating the runtime between 0-10 seconds (in microseconds)
}
Run Code Online (Sandbox Code Playgroud)