众所周知,C/C++在许多情况下都比python快。我在这个方向做了一个测试
我有一个大的(美化的)JSON文件,有2200行。测试包括读取文件、反序列化内存中的数据(我使用字典作为数据结构)和显示内容
我在Python中使用内置的^ a1}库和C++使用外部nlohmannjsLoob进行了测试。
运行了几次之后,我震惊地看到C++占用了0.01秒,Python 3需要大约0.001秒,这几乎快了10倍!p>
我在文档中进行了搜索,但没有找到有关编写json
库所用内容的信息
C++:
#include <iostream>
#include <string.h>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include "nlohmann/json.hpp"
using namespace std;
using json = nlohmann::json;
namespace pt = boost::property_tree;
#include <ctime>
int main()
{
ifstream input;
input.open("input.json");
json json_data;
input >> json_data;
cout << json_data << endl;
return 0;
}
和Python:
import json
from time import time
t1 = time()
with open('output.json','r+') as f:
f = json.load(f)
print(f)
t2 = time()
elapsed = t2 - t1
print('elapsed time: '+str(elapsed))
最后一个问题,json
Python库是用低级语言编写的,这是性能的主要原因,还是纯Python
不是在很多情况下,总是
当然,如果您的C/C++代码编写得很糟糕,那么它的速度可能会很慢
nlohmann
JSON库比其他替代方法慢。它很可能比CPython的实现慢。如果需要速度,请使用其他库话虽如此,请注意基准测试很难。可能的情况是,正如@杰斯珀和@ IDCelv所提到的,编译C++代码时,你只会缺少优化。p>
是的,正如@jornsharpe所指出的,CPython实现是written in C
一个写得不好的库,不管它是用什么语言写的,都能给你带来惊人的速度
< > C++中有几个专门的、高度优化的JSON解析器,包括RAPIDJSON和SIMDJSON,参见最近的比较:https://lemire.me/blog/2020/03/31/we-released-simdjson-0-3-the-fastest-json-parser-in-the-world-is-even-better/
相关问题 更多 >
编程相关推荐