Skip to content

Commit

Permalink
Initial commit. Passed tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
junegunn committed Apr 23, 2012
0 parents commit 08897b4
Show file tree
Hide file tree
Showing 10 changed files with 287 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .gitignore
@@ -0,0 +1,17 @@
*.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
4 changes: 4 additions & 0 deletions Gemfile
@@ -0,0 +1,4 @@
source 'https://rubygems.org'

# Specify your gem's dependencies in lps.gemspec
gemspec
7 changes: 7 additions & 0 deletions Guardfile
@@ -0,0 +1,7 @@
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

guard :test do
watch(%r{^test/test_.+\.rb$})
end

22 changes: 22 additions & 0 deletions LICENSE
@@ -0,0 +1,22 @@
Copyright (c) 2012 Junegunn Choi

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
75 changes: 75 additions & 0 deletions README.md
@@ -0,0 +1,75 @@
# LPS: Loops Per Second

Rate-controlled loop execution.

## Installation

Add this line to your application's Gemfile:

gem 'lps'

And then execute:

$ bundle

Or install it yourself as:

$ gem install lps

## Usage

```ruby
# - Loops 10 times per second
# - Loops for 10 seconds
now = Time.now
LPS.freq(10).while { Time.now - now < 10 }.loop { # do something }

# - Loops 10 times per second
# - Loops indefinitely
LPS.freq(10).loop { # do something }
```

## Breaking out of the loop

```ruby
LPS.freq(10).loop { break if rand(10) == 0 }
```

## Falling behind

With LPS, the given loop block is run synchronously,
so if it takes longer than the calculated interval,
it won't be possible to achieve the desired frequency.

```ruby
12.times.map { |i| 1 << i }.each do |ps|
cnt = 0
now = Time.now
LPS.freq(ps).while { Time.now - now <= 1 }.loop { cnt += 1; sleep 0.01 }

puts [ps, cnt].join ' => '
end
```

```
1 => 1
2 => 2
4 => 4
8 => 8
16 => 16
32 => 32
64 => 64
128 => 98
256 => 98
512 => 99
1024 => 97
2048 => 98
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
8 changes: 8 additions & 0 deletions Rakefile
@@ -0,0 +1,8 @@
#!/usr/bin/env rake
require "bundler/gem_tasks"
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/**/test_*.rb'
test.verbose = true
end
60 changes: 60 additions & 0 deletions lib/lps.rb
@@ -0,0 +1,60 @@
require "lps/version"

class LPS
def self.freq freq
LPS.new :freq => freq
end

def self.while &cond
LPS.new :cond => cond
end

def freq freq
LPS.new(:freq => freq, :cond => @cond)
end

def while &cond
LPS.new(:freq => @freq, :cond => cond)
end

def loop &block
ret = nil
if @freq.nil?
while @cond.call
ret = block.call
end
else
sleep_interval = 1.0 / @freq

nt = Time.now
while @cond.call
nt += sleep_interval
ret = block.call

now = Time.now
diff = nt - now

if diff > 0.01
sleep diff
elsif diff < 0
nt = now
end
end
end
ret
end

def initialize opts = {}
raise ArgumentError.new("Not a Hash") unless opts.is_a?(Hash)

@freq = opts[:freq]
raise ArgumentError.new(
"Frequency must be a positive number (or nil)") unless
@freq.nil? || (@freq.is_a?(Numeric) && @freq > 0)

@cond = opts[:cond] || proc { true }
raise ArgumentError.new("Invalid condition block") unless
@cond.is_a?(Proc)
end
end

3 changes: 3 additions & 0 deletions lib/lps/version.rb
@@ -0,0 +1,3 @@
class LPS
VERSION = "0.0.1"
end
21 changes: 21 additions & 0 deletions lps.gemspec
@@ -0,0 +1,21 @@
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/lps/version', __FILE__)

Gem::Specification.new do |gem|
gem.authors = ["Junegunn Choi"]
gem.email = ["junegunn.c@gmail.com"]
gem.description = %q{Rate-controlled loop}
gem.summary = %q{Rate-controlled loop}
gem.homepage = "https://github.com/junegunn/lps"

gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "lps"
gem.require_paths = ["lib"]
gem.version = LPS::VERSION

gem.add_development_dependency 'test-unit'
gem.add_development_dependency 'guard'
gem.add_development_dependency 'guard-test'
end
70 changes: 70 additions & 0 deletions test/test_lps.rb
@@ -0,0 +1,70 @@
#!/usr/bin/env ruby

require 'rubygems'
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '../lib')
require 'lps'
require 'test-unit'

class TestLPS < Test::Unit::TestCase
def test_lps
duration = 3

[0.2, 10, 20].each do |ps|
cnt = 0

now = Time.now
LPS.while { Time.now - now <= duration }.freq(ps).loop { cnt += 1 }

expected = (duration * ps).to_i
# FIXME: naive assertion
assert (expected-1..expected+1).include?(cnt)
end
end

def test_no_frequency
cnt = 0
now = Time.now
LPS.while { Time.now - now <= 1 }.loop { cnt += 1 }
# FIXME: naive assertion
assert cnt > 1000
end

def test_non_positive_frequency
assert_raise(ArgumentError) { LPS.freq(0) }
assert_raise(ArgumentError) { LPS.freq(-1) }
end

def test_non_number_frequency
assert_raise(ArgumentError) { LPS.freq('freq') }
end

def test_non_proc_cond
assert_raise(ArgumentError) { LPS.while('freq') }
end

def test_return_value
cnt = 0
now = Time.now
ret = LPS.while { Time.now - now <= 1 }.loop { cnt += 1 }
assert_equal cnt, ret
end

def test_loop_break
cnt = 0
LPS.freq(100).loop { break if (cnt += 1) >= 50 }
assert_equal 50, cnt
end

def test_lps_high_freq
20.times.map { |i| 1 << i }.each do |ps|
cnt = 0

now = Time.now
LPS.freq(ps).while { Time.now - now <= 1 }.loop { cnt += 1 }

# TODO: need assertion
puts [ps, cnt].join ' => '
end
end
end

0 comments on commit 08897b4

Please sign in to comment.