I want to send 2000 db requests via node end measure the time of each request. something like this:
var getKey = function(key, i) {
console.time(i);
client.getKey(key, function(val) {
console.timeEnd(i);
}
}
for(var i = 0; i < 2000; i ++) {
getKey(keys[i], i);
}
The problem is it doesn't measure well beacouse of node.it gets to the start time and then waits(because its one thread) - so each measure gets more ms than it really should. How can I fix it? i'm a bit new to NodeJS. thanks.
If you want to measure the time that one request takes and don't want any other operations to interfere with that timing (due to the node.js single threading), then you have to NOT initiate any other requests while you are measuring the time of the one request. Initiate one request and measure the time to get its result.
If you want to measure the time to send and receive N requests/responses, then time the entire block start to finish, not each individual request.
So, it really depends what you want to measure.
Remember, because node.js I/O is generally asynchronous, measuring the time of a single network request is not measuring the CPU time to execute the request - it is measuring the time for the request to be sent over the network, for the receiving server to receive and process the request and then send the result back and for your node.js server to receive the result and then call your code with that result. The host CPU will be idle most of the time because most of the time is just spent waiting for the response to come back over the network.
Per your comments, if you send 2000 requests at once, you are likely to see the later requests slow down because the server you are sending the requests to can't process 2000 requests at once. It will have a limited number of CPUs so once it gets busy processing N requests at once, it will likely queue the remaining requests until one finishes to it can pick up the next one. This queuing may happen at the TCP layer or the server may implement it's own incoming task queue (depends upon server design).