創建了一個包含 10000 個元素的向量,初始化為 5,并使用 chrono 計算時間。 auto startTime = high_resolution_clock::now(); vector<int> v(10000, 5); for(auto& a : v) a *= a; auto stopTime = high_resolution_clock::now(); auto duration = duration_cast<nanoseconds>(stopTime - startTime); cout<<"time: "<<duration.count()*1000<<" microsec\n"; //98362000 microsec創建了一個包含 10000 個元素的列表,初始化為 5。from datetime import datetimestart = datetime.now()a = [5]*10000a = [a ** 2 for a in a]end = datetime.now()diff = end - startprint("time: ", diff.microseconds , " microseconds") //1542 microseconds從上面看,python 顯然是贏家,但作為 c++ 較低級別(我覺得)為什么它的 wrt python 很慢?我知道 chrono 和 datetime 包的時間計算算法可能不同,但是比較向量(c++)和列表(python)的基準是什么?
1 回答

慕工程0101907
TA貢獻1887條經驗 獲得超5個贊
您的 C++ 時間計算不正確。既然你想要微發送,你應該直接詢問它們,而不是你現在的計算。這是更簡單和正確的:
auto duration = duration_cast<microseconds>(stopTime - startTime); cout << "time: " << duration.count() << " microsec\n";
注意:確保您正在測試優化的構建以獲得有用的結果。
添加回答
舉報
0/150
提交
取消