Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily measure elapsed time

I am trying to use time() to measure various points of my program.

What I don't understand is why the values in the before and after are the same? I understand this is not the best way to profile my program, I just want to see how long something take.

printf("**MyProgram::before time= %ld\n", time(NULL));  doSomthing(); doSomthingLong();  printf("**MyProgram::after time= %ld\n", time(NULL)); 

I have tried:

struct timeval diff, startTV, endTV;  gettimeofday(&startTV, NULL);   doSomething(); doSomethingLong();  gettimeofday(&endTV, NULL);   timersub(&endTV, &startTV, &diff);  printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec); 

How do I read a result of **time taken = 0 26339? Does that mean 26,339 nanoseconds = 26.3 msec?

What about **time taken = 4 45025, does that mean 4 seconds and 25 msec?

like image 686
hap497 Avatar asked May 11 '10 06:05

hap497


People also ask

What are used to measure the elapsed time of events?

Per the Android docs SystemClock. elapsedRealtime() is the recommend basis for general purpose interval timing. As others have said, the elapsedRealtime() answer below is correct.

How does CPP calculate elapsed time?

You can use GetTickCount() to get the number of milliseconds that have elapsed since the system was started.

Whats elapsed time?

: the actual time taken (as by a boat or automobile in traveling over a racecourse)

How do you calculate Execution time?

The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.


1 Answers

//***C++11 Style:*** #include <chrono>  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();  std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[µs]" << std::endl; std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << "[ns]" << std::endl; 
like image 188
user3762106 Avatar answered Sep 28 '22 13:09

user3762106