File Coverage

lib/Shannon/Entropy/XS.xs
Criterion Covered Total %
statement 18 18 100.0
branch 8 8 100.0
condition n/a
subroutine n/a
pod n/a
total 26 26 100.0


line stmt bran cond sub pod time code
1             #define PERL_NO_GET_CONTEXT // we'll define thread context if necessary (faster)
2             #include "EXTERN.h" // globals/constant import locations
3             #include "perl.h" // Perl symbols, structures and constants definition
4             #include "XSUB.h" // xsubpp functions and macros
5              
6 5           int makehist (unsigned char * str, int * hist, int len) {
7             int chars[256];
8 5           int histlen = 0;
9 1285 100         for (int i = 0; i < 256; i++) chars[i]=-1;
10 68 100         for (int i = 0; i < len; i++) {
11 63 100         if(chars[(int)str[i]] == -1){
12 57           chars[(int)str[i]] = histlen;
13 57           histlen++;
14             }
15 63           hist[chars[(int)str[i]]]++;
16             }
17 5           return histlen;
18             }
19              
20 5           double entropy (char * str) {
21 5           int len = strlen(str);
22 5           int * hist = (int*)calloc(len,sizeof(int));
23 5           int histlen = makehist(str, hist, len);
24 5           double out = 0;
25 62 100         for (int i = 0; i < histlen; i++) {
26 57           out -= (double)hist[i] / len * log2((double)hist[i] / len);
27             }
28 5           return out;
29             }
30              
31             MODULE = Shannon::Entropy::XS PACKAGE = Shannon::Entropy::XS
32             PROTOTYPES: ENABLE
33              
34             SV *
35             entropy(string)
36             SV * string;
37             CODE:
38 5           RETVAL = newSVnv(entropy(SvPV_nolen(string)));
39             OUTPUT:
40             RETVAL
41