0
所以我得到了一段代码运行,我想提高性能,我发现删除需要很长时间才能完成(大约0.003秒),所以我决定把它放到另一个线程中,然后删除数组。dispatch_async影响代码后续的性能?
现在创建和运行线程所花费的时间比删除数组要快得多,但是现在线程创建后的代码遭受性能影响,运行时间延长了2到3倍。
有没有人知道为什么会发生这种情况,以及我如何提高性能?请注意,我正在使用dispatch_async,因为我之前只编写了一个mac代码,并没有尝试过创建多个线程的其他C/C++库,所以如果有人知道另一个库可以做更好的性能,我会切换到使用它。
clock_t start, end, start2, end2;
start = clock();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
std::set<int> *temp = a;
a = nullptr;
dispatch_async(queue, ^{
delete[] temp;
});
//delete[] a;
end = clock();
a = new std::set<int>[10000];
start2 = clock();
/*
Code here initializes stuff inside the array a
Code here never changes
*/
end2 = clock();
//(end2 - start2/CLOCKS_PER_SEC) is now much longer than it was without multithreading but (end - start)/CLOCKS_PER_SEC is much faster (which is expected)
因此,为什么我有一个临时变量('temp')设置为与'a'相同的指针,然后将'a'设置为空指针,以便可以同时完成删除和创建数组.. ..或者可以它? – TheAmateurProgrammer
任何变量指向什么都没有关系。这是分配和释放内存的机制中的争论,并做必要的内务管理以跟踪堆的状态。没有人知道或关心你的变数。 –
我明白了......那么有没有什么办法可以改善代码的性能,还是我坚持我现在拥有的东西? – TheAmateurProgrammer