Skip to content

Instantly share code, notes, and snippets.

@amka
Last active November 28, 2016 19: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 amka/956bf18acdd87208d48fa79f750c1ae0 to your computer and use it in GitHub Desktop.
Save amka/956bf18acdd87208d48fa79f750c1ae0 to your computer and use it in GitHub Desktop.
Simple app to count lines in file in different language.
#include <stdio.h>
#include <time.h>
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
const char *path = "big.csv";
double startTime = clock();
int linesCount = 0;
FILE *fp = fopen(path, "r");
int bufsize = 32*1024;
char buff[bufsize];
while (fgets(buff, bufsize, fp) != NULL) {
linesCount++;
}
fclose(fp);
double endTime = clock();
double totalTime = (endTime - startTime) / CLOCKS_PER_SEC;
printf("Time: %f s\n", totalTime);
printf("Lines: %d \n", linesCount);
return 0;
}
using System;
using System.IO;
namespace lineStat
{
class MainClass
{
public static void Main(string[] args)
{
var filename = "big.csv";
Console.WriteLine("Count lines in {0}", filename);
var startTime = DateTime.Now;
var linesCount = countLinesInFile(filename);
var spentTime = DateTime.Now - startTime;
Console.WriteLine("Lines count: {0} in {1}", linesCount, spentTime);
}
static int countLinesInFile(string filename)
{
int linesCount = 0;
using (var reader = new StreamReader(filename))
{
while (reader.ReadLine() != null) {
linesCount++;
}
}
return linesCount;
}
}
}
package main
import (
"bytes"
"fmt"
"io"
"os"
"time"
)
func main() {
start_time := time.Now()
file, _ := os.Open("big.csv")
count, _ := lineCounter(file)
elapsed := time.Since(start_time)
fmt.Printf("Lines count: %d in %s\n", count, elapsed)
}
func lineCounter(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}
package me.meamka;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class LinesCount {
public static void main(String[] args) throws IOException {
// write your code here
String filename = "big.csv";
System.out.println("Count lines in " + filename);
long startTime = System.nanoTime();
int linesCount = countLinesInFile(filename);
long endTime = System.nanoTime();
NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.println("Lines count: " + linesCount +" in " + formatter.format((endTime - startTime) / 1000000000d));
}
private static int countLinesInFile(String filename) throws IOException {
int linesCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
while (br.readLine() != null) {
linesCount++;
}
}
return linesCount;
}
}
<?php
function countLinesInFile($filename) {
$f = fopen( 'big.csv', 'r');
$lineCount = 0;
while (!feof($f))
{
if (fgets($f))
$lineCount++;
}
fclose($f);
return $lineCount;
}
function main() {
$start = microtime(true);
$linesCount = countLinesInFile($filename);
$duration = number_format(microtime(true)-$start, 4);
$memory = number_format(memory_get_peak_usage(true),0,'.',' ');
echo "Total lines: $linesCount; Duration: $duration seconds; Memory used: $memory bytes\n";
}
main();
?>
# coding: utf-8
import time
def linesCount(filename):
count = 0
with open(filename, 'r') as reader:
while reader.readline():
count += 1
return count
if __name__ == '__main__':
filename = 'big.csv'
start_time = time.time()
count = linesCount(filename)
end_time = time.time() - start_time
print("Lines count: %s in %s" % (count, end_time))
import Foundation
import Darwin
var path = "big.csv"
let methodStart = NSDate()
var linesCount = 0
let bufsize = 32*1024
var buf = UnsafeMutablePointer<Int8>.allocate(capacity: bufsize)
let filePointer = fopen(path, "r")
while fgets(buf, Int32(bufsize-1), filePointer) != nil {
// print(String.fromCString(CString(buf)))
linesCount += 1
}
fclose(filePointer)
let methodFinish = Date()
let executionTime = methodFinish.timeIntervalSince(methodStart as Date)
print("Execution time: \(executionTime)")
print("Lines Count: \(linesCount)")
@Playermet
Copy link

Playermet commented Nov 28, 2016

Вот этот код в LuaJIT у меня отработал в 8 раз быстрее чем приведенный ранее на C. Кроме того вариант на C показал неправильное число строк - 29194 вместо 13752. Файл - sql, 589 202 717 байт.

local function count_subs(s, sub)
	local c = 0

	local start = 0
	local from, to = string.find(s, sub, start, true)
	while from do
	  c = c + 1
	  start = to + 1
	  from, to = string.find(s, sub, start, true)
	end

	return c
end

local time_b = os.clock()
local lines_n = 0

local file, b = io.open('backup.sql', 'rb')
while true do
	b = file:read(32*1024)
	if b == nil then break end
	lines_n = lines_n + count_subs(b, '\n')
end
file:close()
local time_e = os.clock()

print(lines_n, (time_e - time_b))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment