#!/usr/bin/env newlisp

(println)
(println "Testing UDP communicatiobs with spawned processes")

; benchmark net work functions with spawned processes

; non-blocking simole UDP communications

(set 'N
	(case ostype
		("Linux" 1000)
		("Cygwin" 1000)
		("BSD" 1000)
		("OSX" 10000)
		("Tru64Unix" 1000)
		("Solaris" 1000)
		("SunOS" 1000)
		(true (println ">>>>> UDP Not supported on this OS - will exit") 
			(exit))
	)
)

(set 'cpid (spawn 'r 
	(begin
		(sleep 300)
		(for (i 1 N)
			(sleep 0.2) ; increase if losing to much
			(net-send-udp "localhost" 12345 (string i))
		)
	(exit)
	)
))

(println (sync))

(set 'start (time-of-day))
(set 'counter 0)
(set 'timeout '2000000)
(until finished
	(set 'buff (net-receive-udp 12345 100 timeout))
	(if buff
		(begin
			(inc counter) 
			(print "-> " (first buff) "\r")
			(if (= (int (first buff)) N) (set 'finished true)))
		(begin
			(println "finished ->" (net-error))
			(if (= (first (net-error)) 17)
				(inc start (/ timeout 1000))) ; account for timeout
			(set 'finished true))
	)
)

(set 'duration (- (time-of-day) start))
(println "received " counter  " (" (mul (div counter N) 100) 
        "%) of " N " messages in " duration " ms")
(println (div duration counter) " ms per message")

(abort)

(println ">>>>> Benchmarked UDP API")

(exit)

