As I know in C language in order to multiply an array by a scalar, you have to iterate over each element using a for-loop. And as I know also the source code for the R software environment is written primarily in C. And from there when I have a big matrix in R like mat = matrix(5, nrow = 1100, ncol = 1100)
and then multiply it by a constant and measure the time of this operation, just like so:
t_start = Sys.time()
mat = mat *5
print(Sys.time()-t_start)
output:
Time difference of 0.005984068 secs
But doing the same thing using for-loops, it takes too much time:
t_start = Sys.time()
for(i in 1:1100)
{
for(j in 1:1100)
{
mat[i,j] = mat[i,j] * 5
}
}
print(Sys.time()-t_start)
output:
Time difference of 0.1437349 secs
The second way is ~24 times slower, now I'm assuming that behind the scene the first way is also has been done using for-loops, if so, why the time difference is too big?!
I'm wondering if there is a better way to apply an operation to an entire block of memory in C, without iterating over each element using loops. I would like to get some answers from C language perspective, as I'm working currently with C. And those pieces of R-code was just to show two different ways of doing this that R provides and C do not.