:타이밍
#include <iostream>
#include <sys/time.h>
using namespace std;
int fooVal(int a) {
for (size_t i = 0; i < 1000; ++i) {
++a;
--a;
}
return a;
}
int fooRef(int & a) {
for (size_t i = 0; i < 1000; ++i) {
++a;
--a;
}
return a;
}
int main() {
int a = 0;
struct timeval stop, start;
gettimeofday(&start, NULL);
for (size_t i = 0; i < 10000; ++i) {
fooVal(a);
}
gettimeofday(&stop, NULL);
printf("The loop has taken %lu microseconds\n", stop.tv_usec - start.tv_usec);
gettimeofday(&start, NULL);
for (size_t i = 0; i < 10000; ++i) {
fooRef(a);
}
gettimeofday(&stop, NULL);
printf("The loop has taken %lu microseconds\n", stop.tv_usec - start.tv_usec);
return 0;
}
그것을 fooRef
내부에서 연산을 수행하는 동안 "look up"참조 된 값 때문에 메모리가 fooVal
인 경우보다 더 많은 시간이 걸릴 것으로 예상되었습니다.
The loop has taken 18446744073708648210 microseconds
The loop has taken 99967 microseconds
내가 코드를 실행할 때 그것은과 함께 시간을 만들어 값의 대부분은 서로 가까운
The loop has taken 97275 microseconds
The loop has taken 99873 microseconds
뭔가를 (생성 할 수 있습니다 : 그러나 입증 결과는 나를 위해 예상치 못한하기 fooRef
이 조금 느리다), 가끔씩 첫 번째 실행 결과와 같은 폭발이 발생할 수있다. (fooRef
과 fooVal
루프 모두).
이 이상한 결과를 설명해 주시겠습니까?
UPD : O0 수준이 최적화되었습니다.
OMG! 당신은 정말로'18446744073708648210' 마이크로 초를 기다렸습니까 ?? – WhiZTiM
하려면 @WhiZTiM 물론 아닙니다. 그것은 정말 빨리 실행됩니다. 그러나 데이터는 매우 혼란 스럽습니다. –
최적화를 사용 하시겠습니까? –