Skip to content

Instantly share code, notes, and snippets.

@def-
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save def-/45568077b01d2326a7bc to your computer and use it in GitHub Desktop.
Save def-/45568077b01d2326a7bc to your computer and use it in GitHub Desktop.
Average in Nimrod and Python
# 3.5 seconds
# compute average line length
var count = 0
var sum = 0
for line in stdin.lines:
count += 1
sum += line.len
# Not much faster
#var line = ""
#while stdin.readLine(line):
# count += 1
# sum += line.len
echo "Average line length: ",
if count > 0: sum / count else: 0
# 2.3 seconds
from sys import stdin
# compute average line length
count = 0
sum = 0
for line in stdin:
count += 1
sum += len(line) - 1
if count > 0:
avg = float(sum) / count
else:
avg = 0
print "Average line length: ", avg
# 1.5 seconds
# But fgets does not regard CR, so this is different from readLine
# Same as Python though
proc fgets(c: cstring, n: int, f: TFile): cstring {.
importc: "fgets", header: "<stdio.h>", tags: [FReadIO].}
var buf = cast[cstring](alloc(8192))
proc myReadLine(f: TFile, line: var TaintedString): bool =
setLen(line.string, 0)
result = true
while true:
if fgets(buf, 8192, f) == nil:
result = false
break
if buf[buf.len-1] == '\l':
buf[buf.len-1] = '\0'
add(line, buf)
break
add(line, buf)
# compute average line length
var count = 0
var sum = 0
var line = ""
while stdin.myReadLine(line):
count += 1
sum += line.len
echo "Average line length: ",
if count > 0: sum / count else: 0
# Using a local buffer, slower unfortunately
# But fgets does not regard CR, so this is different from readLine
# Same as Python though
proc fgets(c: cstring, n: int, f: TFile): cstring {.
importc: "fgets", header: "<stdio.h>", tags: [FReadIO].}
proc myReadLine(f: TFile, line: var TaintedString): bool =
var buf: array[8192, char]
setLen(line.string, 0)
result = true
while true:
if fgets(buf, 8192, f) == nil:
result = false
break
if buf[cstring(buf).len-1] == '\l':
buf[cstring(buf).len-1] = '\0'
add(line, cstring(buf))
break
add(line, cstring(buf))
# compute average line length
var count = 0
var sum = 0
var line = ""
while stdin.myReadLine(line):
count += 1
sum += line.len
echo "Average line length: ",
if count > 0: sum / count else: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment