-
-
Save gr33n7007h/4cac4c90d20745b4f0f3a235fcc330e0 to your computer and use it in GitHub Desktop.
Calculate Standard Deviation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
π pry | |
>> handle = Handle.new './libsd.so' | |
=> #<Fiddle::Handle:0x00005646ea646220> | |
>> sd = Function.new handle['standard_deviation'], [TYPE_VOIDP, TYPE_INT], TYPE_FLOAT | |
=> #<Fiddle::Function:0x00005646ea670890 @abi=2, @args=[1, 4], @ptr=140326241698073, @return_type=7> | |
>> arr = [*1..10] | |
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
>> ptr = arr.pack("i#{arr.size}") | |
=> "\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\x00\x00\x00\b\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00" | |
>> sd.(ptr, arr.size) | |
=> 2.872281312942505 | |
>> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <math.h> | |
float standard_deviation(int a[], int size) | |
{ | |
float sum = 0.0, sd = 0.0, m; | |
int i; | |
for(i = 0; i < size; i++) | |
sum += a[i]; | |
m = sum / size; | |
for(i = 0; i < size; i++) | |
sd += pow(a[i] - m, 2); | |
return sqrt(sd / size); | |
} | |
// gcc -g -Wall -shared -o libsd.so -fPIC standard_deviation.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>> def ms_time | |
| s = Process.clock_gettime Process::CLOCK_MONOTONIC, :float_millisecond | |
| yield | |
| Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) - s | |
| end | |
=> :ms_time | |
>> | |
>> handle = Handle.new './libsd.so' | |
=> #<Fiddle::Handle:0x00005610c18d94b0> | |
>> sd = Function.new handle['standard_deviation'], [TYPE_VOIDP, TYPE_INT], TYPE_FLOAT | |
=> #<Fiddle::Function:0x00005610c1908f30 @abi=2, @args=[1, 4], @ptr=140166056644889, @return_type=7> | |
>> arr = [*1..10_000_000]; | |
>> ptr = arr.pack("i#{arr.size}"); | |
>> | |
>> ms_time { sd.(ptr, arr.size) } | |
=> 132.675954002887 | |
>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment