Created
January 3, 2011 19:39
-
-
Save joshpeterson/763832 to your computer and use it in GitHub Desktop.
Compare the performance of a matrix multiplication in JavaScript and native code.
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 <cstdlib> | |
#include <ctime> | |
#include <iostream> | |
// From http://stackoverflow.com/questions/2704521/generate-random-double-numbers-in-c | |
double fRand(double fMin, double fMax) | |
{ | |
double f = (double)rand() / RAND_MAX; | |
return fMin + f * (fMax - fMin); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
int n = 5000; | |
std::clock_t start = std::clock(); | |
double** A = (double**)malloc(sizeof(double*)*n); | |
double* B = (double*)malloc(sizeof(double)*n); | |
std::cout << "Starting" << std::endl; | |
srand(time(NULL)); | |
for (int i = 0; i < n; i++) | |
{ | |
double* row = (double*)malloc(sizeof(double)*n); | |
for (int j = 0; j < n; j++) | |
{ | |
row[j] = fRand(0.0, 1.0); | |
} | |
A[i] = row; | |
B[i] = fRand(0.0, 1.0); | |
} | |
double* X = (double*)malloc(sizeof(double)*n); | |
for (int i = 0; i < n; i++) | |
{ | |
double sum = 0.0; | |
for (int j = 0; j < n; j++) | |
{ | |
sum += A[i][j] * B[i]; | |
} | |
X[i] = sum; | |
} | |
double elapsed = double(std::clock() - start) / CLOCKS_PER_SEC; | |
std::cout << "Done in " << elapsed << "s" << std::endl; | |
return 0; | |
} |
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
<html> | |
<head> | |
<title>Test Matrix</title> | |
<script> | |
window.onload = function() | |
{ | |
alert("Starting"); | |
var start = new Date().getTime(); | |
n = 5000; | |
var A = new Array(n); | |
var B = new Array(n); | |
for (i = 0; i < n; i++) | |
{ | |
var row = new Array(n); | |
for (j = 0; j < n; j++) | |
{ | |
row[j] = Math.random(); | |
} | |
A[i] = row; | |
B[i] = Math.random(); | |
} | |
var X = new Array(n); | |
for (i = 0; i < n; i++) | |
{ | |
var sum = 0; | |
for (j = 0; j < n; j++) | |
{ | |
sum += A[i][j] * B[i]; | |
} | |
X[i] = sum; | |
} | |
var end = new Date().getTime(); | |
var time = (end - start) / 1000; | |
alert("Done in: " + time + "s"); | |
} | |
</script> | |
</head> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment