Skip to main content
 首页 » 编程设计

python /珀尔 : timed loop implementation (also with microseconds)

2025年05月04日12sharpest

我想使用 Perl 和/或 Python 来实现以下 JavaScript 伪代码:

var c=0; 
function timedCount() 
{ 
  c=c+1; 
  print("c=" + c); 
 
  if (c<10)  { 
    var t; 
    t=window.setTimeout("timedCount()",100); 
  } 
} 
 
// main: 
timedCount(); 
print("after timedCount()"); 
 
var i=0; 
for (i=0; i<5; i++) { 
  print("i=" + i); 
  wait(500); //wait 500 ms 
} 

现在,这是一个特别不幸的例子选择作为基础 - 但我只是想不出任何其他语言来提供它:)基本上,有一个“主循环”和一个辅助“循环”( timedCount),两者都以不同的速率计数:main 以 500 ms 周期(通过 wait 实现),timedCount 以 100 ms 周期(实现通过 setInterval)。然而,JavaScript 本质上是单线程的,而不是多线程的 - 因此,没有真正的 sleep/wait/pause 或类似的( 参见 JavaScript Sleep Function - ozzu.com ),这就是为什么上面是伪代码的原因 ;)

然而,通过将主要部分移动到另一个 setInterval 函数,我们可以获得一个可以粘贴并在浏览器 shell 中运行的代码版本,如 JavaScript Shell 1.4 (但不在像 EnvJS/Rhino 这样的终端 shell 中):

var c=0; 
var i=0; 
function timedCount() 
{ 
  c=c+1; 
  print("c=" + c); 
 
  if (c<10)  { 
    var t; 
    t=window.setTimeout("timedCount()",100); 
  } 
} 
 
function mainCount() // 'main' loop 
{ 
  i=i+1; 
  print("i=" + i); 
 
  if (i<5)  { 
    var t; 
    t=window.setTimeout("mainCount()",500); 
  } 
} 
 
// main: 
mainCount(); 
timedCount(); 
print("after timedCount()"); 

... 结果类似这样的输出:

i=1 
c=1 
after timedCount() 
c=2 
c=3 
c=4 
c=5 
c=6 
i=2 
c=7 
c=8 
c=9 
c=10 
i=3 
i=4 
i=5 

...也就是说,主要计数和辅助计数是“交错”/“线程化”/“散布”的,如预期的那样,大约每五个辅助计数就有一个主要计数。

现在是主要问题 - 在 Perl 和 Python 中分别推荐的方法是什么?

  • 此外,Python 或 Perl 是否提供了以跨平台方式以微秒计时分辨率实现上述功能的工具?

非常感谢您的回答,
干杯!

请您参考如下方法:

我能想到的在 Python 中执行此操作的最简单和最通用的方法是使用 Twisted (一个基于事件的网络引擎)来做到这一点。

from twisted.internet import reactor 
from twisted.internet import task 
 
c, i = 0, 0 
def timedCount(): 
    global c 
    c += 1 
    print 'c =', c 
 
def mainCount(): 
    global i 
    i += 1 
    print 'i =', i 
 
c_loop = task.LoopingCall(timedCount) 
i_loop = task.LoopingCall(mainCount) 
c_loop.start(0.1) 
i_loop.start(0.5) 
reactor.run() 

Twisted 有一个高效稳定的事件循环实现,称为 react 器。这使得它是单线程的,并且本质上与上面示例中的 Javascript 非常相似。我使用它来执行类似上述周期性任务的原因是它提供的工具可以让您轻松添加任意数量的复杂周期。

它还提供more tools for scheduling task calls你可能会觉得很有趣。