forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_cache_matrix.R
35 lines (24 loc) · 1.08 KB
/
test_cache_matrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# This script can be run to test the cache matrix implementation
# performance compared to a regular matrix for repeated inversions.
# It first creates a random 1000x1000 matrix and then calculates
# the average time to invert it 10 times for both a normal
# and cache matrix. It then prints the average elapsed time
# (per inversion) to the console.
source("cachematrix.R")
originalMatrix <- replicate(1000, rnorm(1000, 0, 4))
cacheMatrix <- makeCacheMatrix(originalMatrix)
numIterations <- 10
message(sprintf("Calculating average time taken to invert original matrix %d times", numIterations))
printAverageTime <- function(times) {
message(sprintf("Average inverse time is %f seconds", mean(times)))
}
times <- vector(mode = "numeric", length = numIterations)
for (i in 1:numIterations) {
times[i] <- system.time(solve(originalMatrix))[["elapsed"]]
}
printAverageTime(times)
message(sprintf("Calculating average time taken to invert cached matrix %d times", numIterations))
for (i in 1:numIterations) {
times[i] <- system.time(cacheSolve(cacheMatrix))[["elapsed"]]
}
printAverageTime(times)