Created
November 11, 2012 14:40
-
-
Save hadley/4055087 to your computer and use it in GitHub Desktop.
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
IntegerVector table1(const CharacterVector x) { | |
std::map<char*, int> counts; | |
int n = x.length(); | |
for (int i = 0; i < n; i++) { | |
counts[x[i]]++; | |
} | |
// Loop through each element of map and output into named vector | |
IntegerVector out(counts.size()); | |
CharacterVector names(counts.size()); | |
std::map<char*, int>::iterator it; | |
int i; | |
for (i = 0, it = counts.begin(); it != counts.end(); i++, it++) { | |
names[i] = it->first; | |
out[i] = it->second; | |
} | |
out.attr("names") = names; | |
return(out); | |
} |
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
library(Rcpp) | |
cppFunction(' | |
IntegerVector table1(const CharacterVector x) { | |
std::map<std::string, int> counts; | |
std::vector<std::string> vec = as<std::vector<std::string> >(x); | |
int n = x.length(); | |
for (int i = 0; i < n; i++) { | |
counts[vec[i]]++; | |
} | |
// Loop through each element of map and output into named vector | |
IntegerVector out(counts.size()); | |
CharacterVector names(counts.size()); | |
std::map<std::string, int>::iterator it; | |
int i; | |
for (i = 0, it = counts.begin(); it != counts.end(); i++, it++) { | |
names[i] = it->first; | |
out[i] = it->second; | |
} | |
out.attr("names") = names; | |
return(out); | |
} | |
') | |
library(microbenchmark) | |
x <- sample(letters, 1e4, rep = T) | |
microbenchmark( | |
table(x), | |
table1(x) | |
) | |
# About 3x faster |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment