顯而易見的答案是,您的代碼只需要5微秒 執行。可能因爲你從不使用sum
,所以 編譯器將消除任何用於修改其值的代碼(因此 因此是內部循環)。最重要的是,您的測量 可能由clock
的粒度決定。你也 想要測量儘可能大的一段時間:如果兩個電話clock
是 小於約5分鐘的一部分(但當然,我會用很多 我懷疑是 測量調試程序時更短的時間間隔:-))。我的解決方案 (我不是說它是完美的)一般已經把 代碼在虛擬函數中進行測量,派生類 中的函數在基類中什麼都不做, 之類的東西:
class Base
{
static int ourCount;
static double ourTare;
virtual void doRun();
public:
double run();
static void setCount(int count);
};
int Base::ourCount = 0;
double Base::ourTare = 0.0;
void Base::doRun() {}
double Base::run()
{
clock_t start = clock();
for (int count = ourCount; count > 0; -- count)
doRun();
clock_t end = clock();
return (static_cast<double>(end - start)/CLOCKS_PER_SEC - ourTare;
}
void Base::setCount(int count)
{
ourCount = count;
ourTare = 0.0;
// The following has been sufficient in the past. If the
// compiler inlines Base::run, however, it could be
// insufficent. (In my own code, Base::run is in a
// separate translation unit.)`
ourTare = Base().run();
}
class Derived
{
int d;
virtual void doRun();
public:
};
void Derived::doRun()
{
int sum = 0;
for (int i = 1; i <= 100; ++ i) {
sum += i * i;
}
d = sum;
}
然後調用Base::setCount
與計數(東西 簡單的像這樣的,東西少繞一百萬是 無用比),創建導出的實例,並調用它run
到 獲得的總時間秒。如果您想要每次迭代的時間,您可以將它除以 計數。
(A更輕率的答案是,該方案的產出 "5e-006"
因爲編譯器壞了。這不是一個法律 輸出在C任何浮點值++)
'雙SumOfSquare()()'真的? – 2011-05-02 14:55:13
ahh我複製了錯誤的代碼,它必須在第二個括號內 – Anon 2011-05-02 14:57:55
請發佈一個[簡短,自包含的完整示例(請參見sscce.org)](http://sscce.org/)。您的示例可能會縮短以揭示問題的真實性質,缺少至少一行代碼,並且存在編譯錯誤。 – 2011-05-02 15:00:10