我已決定傳球的倍值和由在C基準++用下面的代碼進行比較(克++ 5.4.0):定時使用變量通過引用,並通過在C++值傳遞的
#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
內部的操作時在內存中「查找」了參考值,預計fooRef
執行將花費比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
To @WhiZTiM 當然不是。它運行得非常快,因爲它應該。但數據非常混亂。 –
你打開了優化? –