Skip to content

Commit 3b5ada7

Browse files
author
Dynesshely
committed
✔️ Test: Multi Threads
1 parent bc25e21 commit 3b5ada7

1 file changed

Lines changed: 37 additions & 6 deletions

File tree

Algorithm.UnitTest/HashTest.cs

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
using Algorithm.Interop;
44
using System.Collections.Generic;
55
using System.Threading;
6+
using System.IO;
7+
using System.Diagnostics;
8+
using System.Threading.Tasks;
69

710
namespace Algorithm.UnitTest
811
{
@@ -111,25 +114,53 @@ public void BenchMark_短长度字符串原生Hash测试()
111114
[TestMethod]
112115
public void BenchMark_多线程测试()
113116
{
117+
bool sync = false;
118+
object locker = new();
114119
List<Thread> threads = new();
115-
for(int i = (int)1e8; i < (int)1e8 + 1000; ++i)
120+
Stopwatch reg = new();
121+
TimeSpan sum = new(0);
122+
int runned = 0, times = 10000;
123+
if(sync) reg.Start();
124+
for (int i = (int)1e8; i < (int)1e8 + times; ++i)
116125
{
117126
int id = i;
118127
threads.Add(new Thread(() =>
119128
{
120129
string testData = id.ToString();
130+
Stopwatch st = new();
131+
if (sync) st.Start();
121132
string hashCom = Hash.FromString2Hex(testData);
122-
string hashSrc = Hash.FromString2Hex_WithoutCompress(testData, true);
123-
Console.WriteLine(testData);
124-
Console.WriteLine($"\t{hashSrc}");
125-
Console.WriteLine($"\t{hashCom}");
126-
Console.WriteLine();
133+
if (sync) st.Stop();
134+
string rt = sync ? $"\n\t执行时间: { st.Elapsed}" : "";
135+
string output = $"{testData}{rt}\n\t{hashCom}\n";
136+
if (sync) lock (locker)
137+
{
138+
sum += st.Elapsed;
139+
}
140+
Console.WriteLine(output);
141+
if (sync) Interlocked.Increment(ref runned);
127142
}));
128143
}
144+
if(sync) reg.Stop();
145+
if (sync) Console.WriteLine($"注册用时: {reg.Elapsed}");
129146
foreach (Thread thread in threads)
130147
{
131148
thread.Start();
132149
}
150+
if (sync) while (runned != times) ;
151+
if (sync) Console.WriteLine($"总用时: {sum}\n平均用时: {sum.TotalSeconds * 1.0 / 1000}s");
152+
}
153+
154+
[TestMethod]
155+
public void CPU多核并行执行测试()
156+
{
157+
const int times = 10000;
158+
Stopwatch sw = new();
159+
sw.Start();
160+
Parallel.For((int)1e8, (int)1e8 + times, (i, state) =>
161+
{
162+
163+
});
133164
}
134165
}
135166
}

0 commit comments

Comments
 (0)