【发布时间】:2019-05-31 14:09:28
【问题描述】:
我正在将我的 C# 库转换为 C++。我在整个应用程序中使用了一个 C# Dictionary 变量,当我尝试在两种情况下都使用std::map 而不是字符串作为键时,我感觉到性能上的巨大差异。
使用以下代码,C# Dictionary 耗时 0.022717 秒。 C++ 映射大约需要 3 秒。
C# 字典:
Stopwatch stopWatch = new Stopwatch();
Dictionary<string, int> dict = new Dictionary<string, int>();
stopWatch.Start();
for (int i = 0; i < 100000; i++)
{
dict.Add(i.ToString(), i);
}
stopWatch.Stop();
var op = stopWatch.Elapsed.TotalSeconds.ToString();
C++ 映射:
#include <iostream>
#include <map>
#include <string>
#include <chrono>
using namespace std;
int main()
{
std::map<std::string, int> objMap;
tm* timetr = new tm();
time_t t1 = time(NULL);
localtime_s(timetr, &t1);
for (size_t i = 0; i < 100000; i++)
{
objMap.emplace(std::to_string(i), i);
}
tm* timetr2 = new tm();
time_t t2 = time(NULL);
localtime_s(timetr2, &t2);
time_t tt = t2 - t1;
cout << tt;
string sss = "";
cin >> sss;
}
为什么会有这样的差异?达到相同结果的等效替代方案应该是什么?
【问题讨论】:
-
你是怎么编译c++版本的?您使用什么优化标志?
-
请注意,您使用的是分辨率为 1 秒的
time_t。当我尝试它时,我得到了结果 1。 -
不是答案,而是
tm* timetr2 = new tm();->tm timetr2;。更好地使用std::chrono::high_resolution_clock来测量时间。 -
map<int, int>更好,这样您就不会意外测试字符串性能。 -
你会想看
std::to_string(i),那将是malloc100000 次。
标签: c# c++ performance dictionary stdmap