0

I am trying to display the time that took to bring the search results.

Like Google: (0.52 seconds)

google search result example

My project is built with MVC 4.

This is what comes to my mind. First define rightNow as shown below, then get the time that user performed the search (buttonclickedtime) and then calculate: rightNow - buttonclickedtime to display how long it took.

@{
    var rightNow = DateTime.Now;
    var buttonclickedtime = ??
    var message = rightNow - buttonclickedtime;
 }

 <p>It took @message sec. to fetch the results</p>

So the question is: How can I get the time that user clicked the search button?

g t
  • 7,287
  • 7
  • 50
  • 85
thatthing
  • 676
  • 3
  • 15
  • 39
  • 2
    you can use Stopwatch class for time check – Kamlesh Arya Jun 23 '14 at 07:39
  • 1
    In your controller action, set buttonclickedtime before you fetch the search results. Then you can use the approach you have above. However, be aware that this approach will only measure the time spent on the server, not the time spent receiving and transmitting data between server and client – Rune Jun 23 '14 at 08:00

2 Answers2

2

You can try with Stopwatch

Stopwatch s=new Stopwatch();
s.Start();
//Code to test
s.Stop();
var time= s.ElapsedMilliseconds
Kamlesh Arya
  • 4,864
  • 3
  • 21
  • 28
1

It depends if you load the search result by ajax or not. If yes, then probably best way is to do it using javascript. Attach event listener to the button click and save current date like this:

var element = document.getElementById("yourbutton")    
var before;
element.addEventListener('click', function() { 
    before = new Date();
    // do your ajax here (load results)
}, false);

Then, when you ajax returns you the results, you call

function onAjaxReturn()
{
    var after = new Date();
    // TODO: calculate the difference like res = after - before;    
}

Now you have two dates. How to get the difference and properly display it, check this question - How to calculate date difference in javascript

If you don't load search result using ajax, it would be difficult to get the exact time. You will have to add the event listener for button click as well, then get the current date, somehow serialize it to string (for example) and pass it as parameter to you search request. In codebehind, you will make the search and you will return the datetime string together with you results (do nothing with the string). Then you will have to parse the datetime from string again (in javascript), get current time (after) and callculate the difference like in the link I posted above.

Hope this helps

Community
  • 1
  • 1
Martin Brabec
  • 3,720
  • 2
  • 23
  • 26