jlibtests.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. /*
  14. * Jlib regression tests
  15. *
  16. */
  17. #ifdef _USE_CPPUNIT
  18. #include <memory>
  19. #include "jsem.hpp"
  20. #include "jfile.hpp"
  21. #include "jdebug.hpp"
  22. #include "jset.hpp"
  23. #include "sockfile.hpp"
  24. #include "jqueue.hpp"
  25. #include "jregexp.hpp"
  26. #include "unittests.hpp"
  27. class JlibSemTest : public CppUnit::TestFixture
  28. {
  29. public:
  30. CPPUNIT_TEST_SUITE(JlibSemTest);
  31. CPPUNIT_TEST(testSimple);
  32. CPPUNIT_TEST_SUITE_END();
  33. protected:
  34. void testTimedAvailable(Semaphore & sem)
  35. {
  36. unsigned now = msTick();
  37. sem.wait(100);
  38. unsigned taken = msTick() - now;
  39. //Shouldn't cause a reschedule, definitely shouldn't wait for 100s
  40. ASSERT(taken < 5);
  41. }
  42. void testTimedElapsed(Semaphore & sem, unsigned time)
  43. {
  44. unsigned now = msTick();
  45. sem.wait(time);
  46. unsigned taken = msTick() - now;
  47. VStringBuffer errMsg("values: time: %u, taken: %u", time, taken);
  48. CPPUNIT_ASSERT_MESSAGE(errMsg.str(), taken >= time && taken < 2*time);
  49. PROGLOG("%s", errMsg.str());
  50. }
  51. void testSimple()
  52. {
  53. //Some very basic semaphore tests.
  54. Semaphore sem;
  55. sem.signal();
  56. sem.wait();
  57. testTimedElapsed(sem, 100);
  58. sem.signal();
  59. testTimedAvailable(sem);
  60. sem.reinit(2);
  61. sem.wait();
  62. testTimedAvailable(sem);
  63. testTimedElapsed(sem, 5);
  64. }
  65. };
  66. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSemTest );
  67. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSemTest, "JlibSemTest" );
  68. class JlibSemTestStress : public CppUnit::TestFixture
  69. {
  70. public:
  71. CPPUNIT_TEST_SUITE(JlibSemTestStress);
  72. CPPUNIT_TEST(testSimple);
  73. CPPUNIT_TEST_SUITE_END();
  74. protected:
  75. void testTimedElapsed(Semaphore & sem, unsigned time, unsigned loopCount)
  76. {
  77. unsigned __int64 sumTaken = 0;
  78. unsigned maxTaken = 0;
  79. unsigned timeLimit = 2 * time;
  80. unsigned numberOfOut = 0;
  81. bool isSignaled = false;
  82. PROGLOG("Start loop");
  83. for (int i = 0 ; i <= loopCount; i++)
  84. {
  85. unsigned now = msTick();
  86. if (sem.wait(time))
  87. {
  88. isSignaled = true;
  89. break;
  90. }
  91. unsigned taken = msTick() - now;
  92. sumTaken += taken;
  93. maxTaken = (taken > maxTaken ? taken : maxTaken);
  94. numberOfOut += (taken > timeLimit ? 1 : 0);
  95. }
  96. VStringBuffer errMsg("values: time: %d, loop: %d, sum taken: %llu, average taken: %llu, max taken: %d, out of limit: %d times, signaled: %s",
  97. time, loopCount, sumTaken, sumTaken/loopCount, maxTaken, numberOfOut, (isSignaled ? "yes" : "no"));
  98. CPPUNIT_ASSERT_MESSAGE(errMsg.str(), 0 == numberOfOut && !isSignaled );
  99. PROGLOG("%s", errMsg.str());
  100. }
  101. void testSimple()
  102. {
  103. //Very basic semaphore stress tests.
  104. Semaphore sem;
  105. sem.signal();
  106. if (!sem.wait(1000))
  107. {
  108. VStringBuffer errMsg("Semaphore stalled (%s:%d)", sanitizeSourceFile(__FILE__), __LINE__);
  109. CPPUNIT_FAIL(errMsg.str());
  110. }
  111. testTimedElapsed(sem, 5, 1000);
  112. }
  113. };
  114. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSemTestStress );
  115. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSemTestStress, "JlibSemTestStress" );
  116. /* =========================================================== */
  117. class JlibSetTest : public CppUnit::TestFixture
  118. {
  119. protected:
  120. void testBitsetHelpers()
  121. {
  122. CPPUNIT_ASSERT_EQUAL(0U, countTrailingUnsetBits(1U));
  123. CPPUNIT_ASSERT_EQUAL(31U, countLeadingUnsetBits(1U));
  124. CPPUNIT_ASSERT_EQUAL(1U, getMostSignificantBit(1U));
  125. CPPUNIT_ASSERT_EQUAL(4U, countTrailingUnsetBits(0x110U));
  126. CPPUNIT_ASSERT_EQUAL(23U, countLeadingUnsetBits(0x110U));
  127. CPPUNIT_ASSERT_EQUAL(9U, getMostSignificantBit(0x110U));
  128. CPPUNIT_ASSERT_EQUAL(0U, countTrailingUnsetBits(0xFFFFFFFFU));
  129. CPPUNIT_ASSERT_EQUAL(0U, countLeadingUnsetBits(0xFFFFFFFFU));
  130. CPPUNIT_ASSERT_EQUAL(32U, getMostSignificantBit(0xFFFFFFFFU));
  131. CPPUNIT_ASSERT_EQUAL(52U, countTrailingUnsetBits(I64C(0x1010000000000000U)));
  132. }
  133. void testSet1(bool initial, IBitSet *bs, unsigned start, unsigned numBits, bool setValue, bool clearValue)
  134. {
  135. unsigned end = start+numBits;
  136. if (initial)
  137. bs->incl(start, end-1);
  138. for (unsigned i=start; i < end; i++)
  139. {
  140. ASSERT(bs->test(i) == clearValue);
  141. bs->set(i, setValue);
  142. ASSERT(bs->test(i) == setValue);
  143. bs->set(i+5, setValue);
  144. ASSERT(bs->scan(0, setValue) == i);
  145. ASSERT(bs->scan(i+1, setValue) == i+5);
  146. bs->set(i, clearValue);
  147. bs->set(i+5, clearValue);
  148. //Clearing i+5 above may extend the set - so need to calculate the end carefully
  149. unsigned last = i+5 < end ? end : i + 6;
  150. unsigned match1 = bs->scan(0, setValue);
  151. CPPUNIT_ASSERT_EQUAL((unsigned)(initial ? last : -1), match1);
  152. bs->invert(i);
  153. ASSERT(bs->test(i) == setValue);
  154. bs->invert(i);
  155. ASSERT(bs->test(i) == clearValue);
  156. bool wasSet = bs->testSet(i, setValue);
  157. ASSERT(wasSet == clearValue);
  158. bool wasSet2 = bs->testSet(i, clearValue);
  159. ASSERT(wasSet2 == setValue);
  160. ASSERT(bs->test(i) == clearValue);
  161. bs->set(i, setValue);
  162. unsigned match = bs->scanInvert(0, setValue);
  163. ASSERT(match == i);
  164. ASSERT(bs->test(i) == clearValue);
  165. }
  166. bs->reset();
  167. if (initial)
  168. {
  169. bs->incl(start, end);
  170. bs->excl(start+5, end-5);
  171. }
  172. else
  173. bs->incl(start+5, end-5);
  174. unsigned inclStart = bs->scan(start, setValue);
  175. ASSERT((start+5) == inclStart);
  176. unsigned inclEnd = bs->scan(start+5, clearValue);
  177. ASSERT((end-5) == (inclEnd-1));
  178. }
  179. void testSet(bool initial, unsigned passes, bool timed)
  180. {
  181. unsigned now = msTick();
  182. bool setValue = !initial;
  183. bool clearValue = initial;
  184. const unsigned numBits = 400;
  185. for (unsigned pass=0; pass < passes; pass++)
  186. {
  187. Owned<IBitSet> bs = createThreadSafeBitSet();
  188. testSet1(initial, bs, 0, numBits, setValue, clearValue);
  189. }
  190. if (timed)
  191. {
  192. unsigned elapsed = msTick()-now;
  193. DBGLOG("Bit test (%u) %d passes time taken = %dms", initial, passes, elapsed);
  194. }
  195. now = msTick();
  196. for (unsigned pass=0; pass < passes; pass++)
  197. {
  198. Owned<IBitSet> bs = createBitSet();
  199. testSet1(initial, bs, 0, numBits, setValue, clearValue);
  200. }
  201. if (timed)
  202. {
  203. unsigned elapsed = msTick()-now;
  204. DBGLOG("Bit test [thread-unsafe version] (%u) %d passes time taken = %dms", initial, passes, elapsed);
  205. }
  206. now = msTick();
  207. size32_t bitSetMemSz = getBitSetMemoryRequirement(numBits+5);
  208. MemoryBuffer mb;
  209. void *mem = mb.reserveTruncate(bitSetMemSz);
  210. for (unsigned pass=0; pass < passes; pass++)
  211. {
  212. Owned<IBitSet> bs = createBitSet(bitSetMemSz, mem);
  213. testSet1(initial, bs, 0, numBits, setValue, clearValue);
  214. }
  215. if (timed)
  216. {
  217. unsigned elapsed = msTick()-now;
  218. DBGLOG("Bit test [thread-unsafe version, fixed memory] (%u) %d passes time taken = %dms\n", initial, passes, elapsed);
  219. }
  220. }
  221. };
  222. class JlibSetTestQuick : public JlibSetTest
  223. {
  224. public:
  225. CPPUNIT_TEST_SUITE(JlibSetTestQuick);
  226. CPPUNIT_TEST(testBitsetHelpers);
  227. CPPUNIT_TEST(testSimple);
  228. CPPUNIT_TEST_SUITE_END();
  229. void testSimple()
  230. {
  231. testSet(false, 100, false);
  232. testSet(true, 100, false);
  233. }
  234. };
  235. class JlibSetTestStress : public JlibSetTest
  236. {
  237. public:
  238. CPPUNIT_TEST_SUITE(JlibSetTestStress);
  239. CPPUNIT_TEST(testParallel);
  240. CPPUNIT_TEST(testSimple);
  241. CPPUNIT_TEST_SUITE_END();
  242. void testSimple()
  243. {
  244. testSet(false, 10000, true);
  245. testSet(true, 10000, true);
  246. }
  247. protected:
  248. class CBitThread : public CSimpleInterfaceOf<IInterface>, implements IThreaded
  249. {
  250. IBitSet &bitSet;
  251. unsigned startBit, numBits;
  252. bool initial, setValue, clearValue;
  253. CThreaded threaded;
  254. Owned<IException> exception;
  255. CppUnit::Exception *cppunitException;
  256. public:
  257. CBitThread(IBitSet &_bitSet, unsigned _startBit, unsigned _numBits, bool _initial)
  258. : threaded("CBitThread", this), bitSet(_bitSet), startBit(_startBit), numBits(_numBits), initial(_initial)
  259. {
  260. cppunitException = NULL;
  261. setValue = !initial;
  262. clearValue = initial;
  263. }
  264. void start() { threaded.start(); }
  265. void join()
  266. {
  267. threaded.join();
  268. if (exception)
  269. throw exception.getClear();
  270. else if (cppunitException)
  271. throw cppunitException;
  272. }
  273. virtual void threadmain() override
  274. {
  275. try
  276. {
  277. unsigned endBit = startBit+numBits-1;
  278. if (initial)
  279. bitSet.incl(startBit, endBit);
  280. for (unsigned i=startBit; i < endBit; i++)
  281. {
  282. ASSERT(bitSet.test(i) == clearValue);
  283. bitSet.set(i, setValue);
  284. ASSERT(bitSet.test(i) == setValue);
  285. if (i < (endBit-1))
  286. ASSERT(bitSet.scan(i, clearValue) == i+1); // find next unset (should be i+1)
  287. bitSet.set(i, clearValue);
  288. bitSet.invert(i);
  289. ASSERT(bitSet.test(i) == setValue);
  290. bitSet.invert(i);
  291. ASSERT(bitSet.test(i) == clearValue);
  292. bool wasSet = bitSet.testSet(i, setValue);
  293. ASSERT(wasSet == clearValue);
  294. bool wasSet2 = bitSet.testSet(i, clearValue);
  295. ASSERT(wasSet2 == setValue);
  296. ASSERT(bitSet.test(i) == clearValue);
  297. bitSet.set(i, setValue);
  298. unsigned match = bitSet.scanInvert(startBit, setValue);
  299. ASSERT(match == i);
  300. ASSERT(bitSet.test(i) == clearValue);
  301. }
  302. }
  303. catch (IException *e)
  304. {
  305. exception.setown(e);
  306. }
  307. catch (CppUnit::Exception &e)
  308. {
  309. cppunitException = e.clone();
  310. }
  311. }
  312. };
  313. unsigned testParallelRun(IBitSet &bitSet, unsigned nThreads, unsigned bitsPerThread, bool initial)
  314. {
  315. IArrayOf<CBitThread> bitThreads;
  316. unsigned bitStart = 0;
  317. unsigned bitEnd = 0;
  318. for (unsigned t=0; t<nThreads; t++)
  319. {
  320. bitThreads.append(* new CBitThread(bitSet, bitStart, bitsPerThread, initial));
  321. bitStart += bitsPerThread;
  322. }
  323. unsigned now = msTick();
  324. for (unsigned t=0; t<nThreads; t++)
  325. bitThreads.item(t).start();
  326. Owned<IException> exception;
  327. CppUnit::Exception *cppunitException = NULL;
  328. for (unsigned t=0; t<nThreads; t++)
  329. {
  330. try
  331. {
  332. bitThreads.item(t).join();
  333. }
  334. catch (IException *e)
  335. {
  336. EXCLOG(e, NULL);
  337. if (!exception)
  338. exception.setown(e);
  339. else
  340. e->Release();
  341. }
  342. catch (CppUnit::Exception *e)
  343. {
  344. cppunitException = e;
  345. }
  346. }
  347. if (exception)
  348. throw exception.getClear();
  349. else if (cppunitException)
  350. throw *cppunitException;
  351. return msTick()-now;
  352. }
  353. void testSetParallel(bool initial)
  354. {
  355. unsigned numBits = 1000000; // 10M
  356. unsigned nThreads = getAffinityCpus();
  357. unsigned bitsPerThread = numBits/nThreads;
  358. bitsPerThread = ((bitsPerThread + (BitsPerItem-1)) / BitsPerItem) * BitsPerItem; // round up to multiple of BitsPerItem
  359. numBits = bitsPerThread*nThreads; // round
  360. fprintf(stdout, "testSetParallel, testing bit set of size : %d, nThreads=%d\n", numBits, nThreads);
  361. Owned<IBitSet> bitSet = createThreadSafeBitSet();
  362. unsigned took = testParallelRun(*bitSet, nThreads, bitsPerThread, initial);
  363. fprintf(stdout, "Thread safe parallel bit set test (%u) time taken = %dms\n", initial, took);
  364. size32_t bitSetMemSz = getBitSetMemoryRequirement(numBits);
  365. MemoryBuffer mb;
  366. void *mem = mb.reserveTruncate(bitSetMemSz);
  367. bitSet.setown(createBitSet(bitSetMemSz, mem));
  368. took = testParallelRun(*bitSet, nThreads, bitsPerThread, initial);
  369. fprintf(stdout, "Thread unsafe parallel bit set test (%u) time taken = %dms\n", initial, took);
  370. }
  371. void testParallel()
  372. {
  373. testSetParallel(false);
  374. testSetParallel(true);
  375. }
  376. };
  377. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSetTestQuick );
  378. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSetTestQuick, "JlibSetTestQuick" );
  379. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSetTestStress );
  380. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSetTestStress, "JlibSetTestStress" );
  381. /* =========================================================== */
  382. class JlibFileIOTestTiming : public CppUnit::TestFixture
  383. {
  384. protected:
  385. unsigned rs, nr10pct, nr150pct;
  386. char *record;
  387. StringBuffer tmpfile;
  388. CPPUNIT_TEST_SUITE( JlibFileIOTestTiming );
  389. CPPUNIT_TEST(testIOSmall);
  390. CPPUNIT_TEST(testIOLarge);
  391. CPPUNIT_TEST_SUITE_END();
  392. public:
  393. JlibFileIOTestTiming()
  394. {
  395. HardwareInfo hdwInfo;
  396. getHardwareInfo(hdwInfo);
  397. rs = 65536;
  398. unsigned nr = (unsigned)(1024.0 * (1024.0 * (double)hdwInfo.totalMemory / (double)rs));
  399. nr10pct = nr / 10;
  400. nr150pct = (unsigned)((double)nr * 1.5);
  401. record = (char *)malloc(rs);
  402. for (unsigned i=0;i<rs;i++)
  403. record[i] = 'a';
  404. record[rs-1] = '\n';
  405. tmpfile.set("JlibFileIOTest.txt");
  406. }
  407. ~JlibFileIOTestTiming()
  408. {
  409. free(record);
  410. }
  411. protected:
  412. void testIO(unsigned nr, const char *server)
  413. {
  414. IFile *ifile;
  415. IFileIO *ifileio;
  416. unsigned fsize = (unsigned)(((double)nr * (double)rs) / (1024.0 * 1024.0));
  417. fflush(NULL);
  418. fprintf(stdout,"\n");
  419. fflush(NULL);
  420. for(int j=0; j<2; j++)
  421. {
  422. if (j==0)
  423. fprintf(stdout, "File size: %d (MB) Cache, ", fsize);
  424. else
  425. fprintf(stdout, "\nFile size: %d (MB) Nocache, ", fsize);
  426. if (server != NULL)
  427. {
  428. SocketEndpoint ep;
  429. ep.set(server, 7100);
  430. ifile = createRemoteFile(ep, tmpfile);
  431. fprintf(stdout, "Remote: (%s)\n", server);
  432. }
  433. else
  434. {
  435. ifile = createIFile(tmpfile);
  436. fprintf(stdout, "Local:\n");
  437. }
  438. ifile->remove();
  439. unsigned st = msTick();
  440. IFEflags extraFlags = IFEcache;
  441. if (j==1)
  442. extraFlags = IFEnocache;
  443. ifileio = ifile->open(IFOcreate, extraFlags);
  444. #if 0 // for testing default and explicitly set share mode to Windows dafilesrv
  445. if (server != NULL)
  446. ifile->setShareMode((IFSHmode)IFSHread);
  447. #endif
  448. try
  449. {
  450. ifile->setFilePermissions(0666);
  451. }
  452. catch (...)
  453. {
  454. fprintf(stdout, "ifile->setFilePermissions() exception\n");
  455. }
  456. unsigned iter = nr / 40;
  457. if (iter < 1)
  458. iter = 1;
  459. __int64 pos = 0;
  460. for (unsigned i=0;i<nr;i++)
  461. {
  462. ifileio->write(pos, rs, record);
  463. pos += rs;
  464. if ((i % iter) == 0)
  465. {
  466. fprintf(stdout,".");
  467. fflush(NULL);
  468. }
  469. }
  470. ifileio->close();
  471. double rsec = (double)(msTick() - st)/1000.0;
  472. unsigned iorate = (unsigned)((double)fsize / rsec);
  473. fprintf(stdout, "\nwrite - elapsed time = %6.2f (s) iorate = %4d (MB/s)\n", rsec, iorate);
  474. st = msTick();
  475. extraFlags = IFEcache;
  476. if (j==1)
  477. extraFlags = IFEnocache;
  478. ifileio = ifile->open(IFOread, extraFlags);
  479. pos = 0;
  480. for (unsigned i=0;i<nr;i++)
  481. {
  482. ifileio->read(pos, rs, record);
  483. pos += rs;
  484. if ((i % iter) == 0)
  485. {
  486. fprintf(stdout,".");
  487. fflush(NULL);
  488. }
  489. }
  490. ifileio->close();
  491. rsec = (double)(msTick() - st)/1000.0;
  492. iorate = (unsigned)((double)fsize / rsec);
  493. fprintf(stdout, "\nread -- elapsed time = %6.2f (s) iorate = %4d (MB/s)\n", rsec, iorate);
  494. ifileio->Release();
  495. ifile->remove();
  496. ifile->Release();
  497. }
  498. }
  499. void testIOSmall()
  500. {
  501. testIO(nr10pct, NULL);
  502. }
  503. void testIOLarge()
  504. {
  505. testIO(nr150pct, NULL);
  506. }
  507. };
  508. class JlibFileIOTestStress : public JlibFileIOTestTiming
  509. {
  510. protected:
  511. CPPUNIT_TEST_SUITE( JlibFileIOTestStress );
  512. CPPUNIT_TEST(testIORemote);
  513. CPPUNIT_TEST_SUITE_END();
  514. void testIORemote()
  515. {
  516. const char * server = ".";
  517. testIO(nr10pct, server);
  518. }
  519. };
  520. CPPUNIT_TEST_SUITE_REGISTRATION( JlibFileIOTestTiming );
  521. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibFileIOTestTiming, "JlibFileIOTestTiming" );
  522. CPPUNIT_TEST_SUITE_REGISTRATION( JlibFileIOTestStress );
  523. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibFileIOTestTiming, "JlibFileIOTestStress" );
  524. /* =========================================================== */
  525. class JlibStringBufferTiming : public CppUnit::TestFixture
  526. {
  527. CPPUNIT_TEST_SUITE( JlibStringBufferTiming );
  528. CPPUNIT_TEST(testSwap);
  529. CPPUNIT_TEST_SUITE_END();
  530. public:
  531. void testSwap()
  532. {
  533. StringBuffer l;
  534. StringBuffer r;
  535. for (unsigned len=0; len<40; len++)
  536. {
  537. const unsigned numIter = 100000000;
  538. cycle_t start = get_cycles_now();
  539. for (unsigned pass=0; pass < numIter; pass++)
  540. {
  541. l.swapWith(r);
  542. }
  543. cycle_t elapsed = get_cycles_now() - start;
  544. DBGLOG("Each iteration of size %u took %.2f nanoseconds", len, (double)cycle_to_nanosec(elapsed) / numIter);
  545. l.append("a");
  546. r.append("b");
  547. }
  548. }
  549. };
  550. CPPUNIT_TEST_SUITE_REGISTRATION( JlibStringBufferTiming );
  551. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibStringBufferTiming, "JlibStringBufferTiming" );
  552. /* =========================================================== */
  553. static const unsigned split4_2[] = {0, 2, 4 };
  554. static const unsigned split100_2[] = {0, 50, 100 };
  555. static const unsigned split100_10[] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
  556. static const unsigned split7_10[] = {0,1,1,2,3,3,4,5,6,6,7 };
  557. static const unsigned split10_3[] = {0,3,7,10 };
  558. static const unsigned split58_10[] = {0,6,12,17,23,29,35,41,46,52,58 };
  559. static const unsigned split9_2T[] = { 0,5,9 };
  560. static const unsigned split9_2F[] = { 0,4,9 };
  561. static const unsigned split15_3[] = { 0,5,10,15 };
  562. class JlibQuantileTest : public CppUnit::TestFixture
  563. {
  564. CPPUNIT_TEST_SUITE( JlibQuantileTest );
  565. CPPUNIT_TEST(testQuantile);
  566. CPPUNIT_TEST(testRandom);
  567. CPPUNIT_TEST_SUITE_END();
  568. public:
  569. JlibQuantileTest()
  570. {
  571. }
  572. void testQuantilePos(unsigned numItems, unsigned numDivisions, bool roundUp, const unsigned * expected)
  573. {
  574. if (numDivisions == 0)
  575. return;
  576. QuantilePositionIterator iter(numItems, numDivisions, roundUp);
  577. QuantileFilterIterator filter(numItems, numDivisions, roundUp);
  578. unsigned prevPos = 0;
  579. iter.first();
  580. for (unsigned i=0; i <= numDivisions; i++)
  581. {
  582. //Check the values from the quantile iterator match those that are expected
  583. unsigned pos = (unsigned)iter.get();
  584. #if 0
  585. printf("(%d,%d) %d=%d\n", numItems, numDivisions, i, pos);
  586. #endif
  587. if (expected)
  588. CPPUNIT_ASSERT_EQUAL(expected[i], pos);
  589. //Check that the quantile filter correctly returns true and false for subsequent calls.
  590. while (prevPos < pos)
  591. {
  592. CPPUNIT_ASSERT(!filter.get());
  593. filter.next();
  594. prevPos++;
  595. }
  596. if (prevPos == pos)
  597. {
  598. CPPUNIT_ASSERT(filter.get());
  599. filter.next();
  600. prevPos++;
  601. }
  602. iter.next();
  603. }
  604. }
  605. void testQuantile()
  606. {
  607. testQuantilePos(4, 2, false, split4_2);
  608. testQuantilePos(100, 2, false, split100_2);
  609. testQuantilePos(100, 10, false, split100_10);
  610. testQuantilePos(7, 10, false, split7_10);
  611. testQuantilePos(10, 3, false, split10_3);
  612. testQuantilePos(10, 3, true, split10_3);
  613. testQuantilePos(58, 10, false, split58_10);
  614. //testQuantilePos(9, 2, true, split9_2T);
  615. testQuantilePos(9, 2, false, split9_2F);
  616. testQuantilePos(15, 3, false, split15_3);
  617. testQuantilePos(1231, 57, false, NULL);
  618. testQuantilePos(1, 63, false, NULL);
  619. testQuantilePos(10001, 17, false, NULL);
  620. }
  621. void testRandom()
  622. {
  623. //test various random combinations to ensure the results are consistent.
  624. for (unsigned i=0; i < 10; i++)
  625. testQuantilePos(random() % 1000000, random() % 10000, true, NULL);
  626. }
  627. };
  628. CPPUNIT_TEST_SUITE_REGISTRATION( JlibQuantileTest );
  629. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibQuantileTest, "JlibQuantileTest" );
  630. /* =========================================================== */
  631. class JlibReaderWriterTestTiming : public CppUnit::TestFixture
  632. {
  633. CPPUNIT_TEST_SUITE(JlibReaderWriterTestTiming);
  634. CPPUNIT_TEST(testCombinations);
  635. CPPUNIT_TEST_SUITE_END();
  636. const static unsigned spinScaling = 1000;
  637. static unsigned spinCalculation(unsigned prev, unsigned scale)
  638. {
  639. unsigned value = prev;
  640. for (unsigned i = 0; i < scale*spinScaling; i++)
  641. {
  642. value = (value * 0x1234FEDB + 0x87654321);
  643. }
  644. return value;
  645. }
  646. class Reader : public Thread
  647. {
  648. public:
  649. Reader(IRowQueue & _source, Semaphore & _doneSem, unsigned _workScale)
  650. : Thread("Reader"), source(_source), doneSem(_doneSem), workScale(_workScale), work(0)
  651. {
  652. }
  653. virtual int run()
  654. {
  655. for (;;)
  656. {
  657. const void * next;
  658. if (!source.dequeue(next))
  659. break;
  660. if (!next)
  661. break;
  662. std::atomic<byte> * value = (std::atomic<byte> *)next;
  663. (*value)++;
  664. if (workScale)
  665. work = spinCalculation(work, workScale);
  666. }
  667. doneSem.signal();
  668. return 0;
  669. }
  670. private:
  671. IRowQueue & source;
  672. Semaphore & doneSem;
  673. volatile unsigned work;
  674. unsigned workScale;
  675. };
  676. class WriterBase : public Thread
  677. {
  678. public:
  679. WriterBase(IRowQueue & _target, size_t _len, byte * _buffer, Semaphore & _startSem, Semaphore & _doneSem, unsigned _workScale)
  680. : Thread("Writer"), target(_target), len(_len), buffer(_buffer), startSem(_startSem), doneSem(_doneSem), workScale(_workScale), work(0)
  681. {
  682. }
  683. protected:
  684. size_t len;
  685. byte * buffer;
  686. IRowQueue & target;
  687. Semaphore & startSem;
  688. Semaphore & doneSem;
  689. volatile unsigned work;
  690. unsigned workScale;
  691. };
  692. class Writer : public WriterBase
  693. {
  694. public:
  695. Writer(IRowQueue & _target, size_t _len, byte * _buffer, Semaphore & _startSem, Semaphore & _doneSem, unsigned _workScale)
  696. : WriterBase(_target, _len, _buffer, _startSem, _doneSem, _workScale)
  697. {
  698. }
  699. virtual int run()
  700. {
  701. startSem.wait();
  702. for (size_t i = 0; i < len; i++)
  703. {
  704. if (workScale)
  705. work = spinCalculation(work, workScale);
  706. target.enqueue(buffer + i);
  707. }
  708. target.noteWriterStopped();
  709. doneSem.signal();
  710. return 0;
  711. }
  712. };
  713. public:
  714. const static size_t bufferSize = 0x100000;//0x100000*64;
  715. void testQueue(IRowQueue & queue, unsigned numProducers, unsigned numConsumers, unsigned queueElements, unsigned readerWork, unsigned writerWork)
  716. {
  717. const size_t sizePerProducer = bufferSize / numProducers;
  718. const size_t testSize = sizePerProducer * numProducers;
  719. OwnedMalloc<byte> buffer(bufferSize, true);
  720. Semaphore startSem;
  721. Semaphore writerDoneSem;
  722. Semaphore stopSem;
  723. Reader * * consumers = new Reader *[numConsumers];
  724. for (unsigned i2 = 0; i2 < numConsumers; i2++)
  725. {
  726. consumers[i2] = new Reader(queue, stopSem, readerWork);
  727. consumers[i2]->start();
  728. }
  729. WriterBase * * producers = new WriterBase *[numProducers];
  730. for (unsigned i1 = 0; i1 < numProducers; i1++)
  731. {
  732. producers[i1] = new Writer(queue, sizePerProducer, buffer + i1 * sizePerProducer, startSem, writerDoneSem, writerWork);
  733. producers[i1]->start();
  734. }
  735. cycle_t startTime = get_cycles_now();
  736. //Start the writers
  737. startSem.signal(numProducers);
  738. //Wait for the writers to complete
  739. for (unsigned i7 = 0; i7 < numProducers; i7++)
  740. writerDoneSem.wait();
  741. //Wait for the readers to complete
  742. for (unsigned i3 = 0; i3 < numConsumers; i3++)
  743. stopSem.wait();
  744. cycle_t stopTime = get_cycles_now();
  745. //All bytes should have been changed to 1, if not a queue item got lost.
  746. unsigned failures = 0;
  747. unsigned numClear = 0;
  748. size_t failPos = ~(size_t)0;
  749. byte failValue = 0;
  750. for (size_t pos = 0; pos < testSize; pos++)
  751. {
  752. if (buffer[pos] != 1)
  753. {
  754. failures++;
  755. if (failPos == ~(size_t)0)
  756. {
  757. failPos = pos;
  758. failValue = buffer[pos];
  759. }
  760. }
  761. if (buffer[pos] == 0)
  762. numClear++;
  763. }
  764. unsigned timeMs = cycle_to_nanosec(stopTime - startTime) / 1000000;
  765. unsigned expectedReadWorkTime = (unsigned)(((double)unitWorkTimeMs * readerWork) / numConsumers);
  766. unsigned expectedWriteWorkTime = (unsigned)(((double)unitWorkTimeMs * writerWork) / numProducers);
  767. unsigned expectedWorkTime = std::max(expectedReadWorkTime, expectedWriteWorkTime);
  768. if (failures)
  769. {
  770. printf("Fail: Test %u producers %u consumers %u queueItems %u(%u) mismatches fail(@%u=%u)\n", numProducers, numConsumers, queueElements, failures, numClear, (unsigned)failPos, failValue);
  771. ASSERT(failures == 0);
  772. }
  773. else
  774. printf("Pass: Test %u(@%u) producers %u(@%u) consumers %u queueItems in %ums [%dms]\n", numProducers, writerWork, numConsumers, readerWork, queueElements, timeMs, timeMs-expectedWorkTime);
  775. for (unsigned i4 = 0; i4 < numConsumers; i4++)
  776. {
  777. consumers[i4]->join();
  778. consumers[i4]->Release();
  779. }
  780. delete[] consumers;
  781. for (unsigned i5 = 0; i5 < numProducers; i5++)
  782. {
  783. producers[i5]->join();
  784. producers[i5]->Release();
  785. }
  786. delete[] producers;
  787. }
  788. void testQueue(unsigned numProducers, unsigned numConsumers, unsigned numElements = 0, unsigned readWork = 0, unsigned writeWork = 0)
  789. {
  790. unsigned queueElements = (numElements != 0) ? numElements : (numProducers + numConsumers) * 2;
  791. Owned<IRowQueue> queue = createRowQueue(numConsumers, numProducers, queueElements, 0);
  792. testQueue(*queue, numProducers, numConsumers, queueElements, readWork, writeWork);
  793. }
  794. void testWorkQueue(unsigned numProducers, unsigned numConsumers, unsigned numElements)
  795. {
  796. for (unsigned readWork = 1; readWork <= 8; readWork = readWork * 2)
  797. {
  798. for (unsigned writeWork = 1; writeWork <= 8; writeWork = writeWork * 2)
  799. {
  800. testQueue(numProducers, numConsumers, numElements, readWork, writeWork);
  801. }
  802. }
  803. }
  804. void testCombinations()
  805. {
  806. // 1:1
  807. for (unsigned i=0; i < 10; i++)
  808. testQueue(1, 1, 10);
  809. //One to Many
  810. testQueue(1, 10, 5);
  811. testQueue(1, 5, 5);
  812. testQueue(1, 5, 10);
  813. testQueue(1, 127, 10);
  814. testQueue(1, 127, 127);
  815. //Many to One
  816. testQueue(10, 1, 5);
  817. testQueue(5, 1, 5);
  818. testQueue(5, 1, 10);
  819. testQueue(127, 1, 127);
  820. cycle_t startTime = get_cycles_now();
  821. volatile unsigned value = 0;
  822. for (unsigned pass = 0; pass < 10; pass++)
  823. {
  824. for (unsigned i2 = 0; i2 < bufferSize; i2++)
  825. value = spinCalculation(value, 1);
  826. }
  827. cycle_t stopTime = get_cycles_now();
  828. unitWorkTimeMs = cycle_to_nanosec(stopTime - startTime) / (1000000 * 10);
  829. printf("Work(1) takes %ums\n", unitWorkTimeMs);
  830. //How does it scale with number of queue elements?
  831. for (unsigned elem = 16; elem < 256; elem *= 2)
  832. {
  833. testQueue(16, 1, elem, 1, 1);
  834. }
  835. #if 1
  836. //Many to Many
  837. for (unsigned readWork = 1; readWork <= 8; readWork = readWork * 2)
  838. {
  839. for (unsigned writeWork = 1; writeWork <= 8; writeWork = writeWork * 2)
  840. {
  841. testQueue(1, 1, 63, readWork, writeWork);
  842. testQueue(1, 2, 63, readWork, writeWork);
  843. testQueue(1, 4, 63, readWork, writeWork);
  844. testQueue(1, 8, 63, readWork, writeWork);
  845. testQueue(1, 16, 63, readWork, writeWork);
  846. testQueue(2, 1, 63, readWork, writeWork);
  847. testQueue(4, 1, 63, readWork, writeWork);
  848. testQueue(8, 1, 63, readWork, writeWork);
  849. testQueue(16, 1, 63, readWork, writeWork);
  850. testQueue(2, 2, 63, readWork, writeWork);
  851. testQueue(4, 4, 63, readWork, writeWork);
  852. testQueue(8, 8, 63, readWork, writeWork);
  853. testQueue(16, 8, 63, readWork, writeWork);
  854. testQueue(16, 16, 63, readWork, writeWork);
  855. testQueue(32, 1, 63, readWork, writeWork);
  856. testQueue(64, 1, 63, readWork, writeWork);
  857. testQueue(1, 32, 63, readWork, writeWork);
  858. testQueue(1, 64, 63, readWork, writeWork);
  859. }
  860. }
  861. #else
  862. //Many to Many
  863. testWorkQueue(1, 1, 63);
  864. testWorkQueue(1, 2, 63);
  865. testWorkQueue(1, 4, 63);
  866. testWorkQueue(1, 8, 63);
  867. testWorkQueue(1, 16, 63);
  868. testWorkQueue(2, 1, 63);
  869. testWorkQueue(4, 1, 63);
  870. testWorkQueue(8, 1, 63);
  871. testWorkQueue(16, 1, 63);
  872. testWorkQueue(2, 2, 63);
  873. testWorkQueue(4, 4, 63);
  874. testWorkQueue(8, 8, 63);
  875. #endif
  876. testQueue(2, 2, 4);
  877. testQueue(2, 2, 8);
  878. testQueue(2, 2, 16);
  879. testQueue(2, 2, 32);
  880. testQueue(2, 2, 100);
  881. }
  882. protected:
  883. unsigned unitWorkTimeMs;
  884. };
  885. CPPUNIT_TEST_SUITE_REGISTRATION(JlibReaderWriterTestTiming);
  886. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibReaderWriterTestTiming, "JlibReaderWriterTestTiming");
  887. /* =========================================================== */
  888. class JlibWildMatchBase : public CppUnit::TestFixture
  889. {
  890. protected:
  891. void testSet(unsigned length, const char * const * patterns, bool reportTiming)
  892. {
  893. std::unique_ptr<char[]> search(generateSearchString(length));
  894. CCycleTimer timer;
  895. testPatterns(search.get(), patterns);
  896. if (reportTiming)
  897. printf("%u: %u ms\n", length, timer.elapsedMs());
  898. }
  899. char * generateSearchString(size_t len)
  900. {
  901. char * target = new char[len+1];
  902. fillSearchString(target, len);
  903. target[len] = 0;
  904. return target;
  905. }
  906. void fillSearchString(char * target, size_t len)
  907. {
  908. for (unsigned repeat=0; ; repeat++)
  909. {
  910. for (unsigned char fill = 'a'; fill <= 'z'; fill++)
  911. {
  912. for (unsigned i=0; i < repeat; i++)
  913. {
  914. *target++ = fill;
  915. if (--len == 0)
  916. return;
  917. }
  918. }
  919. }
  920. }
  921. void testPatterns(const char * search, const char * const * patterns)
  922. {
  923. for (const char * const * cur = patterns; *cur; cur++)
  924. {
  925. const char * pattern = *cur;
  926. bool expected = true;
  927. bool nocase = false;
  928. if (*pattern == '!')
  929. {
  930. expected = false;
  931. pattern++;
  932. }
  933. if (*pattern == '~')
  934. {
  935. nocase = true;
  936. pattern++;
  937. }
  938. bool evaluated = WildMatch(search, pattern, nocase);
  939. CPPUNIT_ASSERT_EQUAL_MESSAGE(pattern, expected, evaluated);
  940. }
  941. }
  942. };
  943. const char * const patterns10 [] = {
  944. "!a",
  945. "abcdefghij",
  946. "??????????",
  947. "?*c?*e*",
  948. "!??*b?*h*",
  949. "a*",
  950. "*j",
  951. "a*j",
  952. "a**j",
  953. "a***************j",
  954. "abcde*fghij",
  955. "!abcde*?*fghij",
  956. "*a*j*",
  957. "*a*c*e*g*j*",
  958. "a?c?e?g??j",
  959. "a?c?e?g?*?j",
  960. "!~A",
  961. "!A*",
  962. "~A*",
  963. "~*J",
  964. "~A*J",
  965. "~A**J",
  966. "~A***************J",
  967. "~*A*J*",
  968. "~*A*C*E*G*J*",
  969. "~*A*B*C*D*E*F*G*H*I*J*",
  970. "~*A*?*?*?*J*",
  971. "~*A*?C*?E*?*J*",
  972. "~*A*C?*E?*?*J*",
  973. "!~*A*.B*C*D*E*F*G*H*I*J*",
  974. nullptr
  975. };
  976. const char * const patterns100 [] = {
  977. "a*",
  978. "*h",
  979. "a*h",
  980. "a**h",
  981. "a***************h",
  982. "*a*j*",
  983. "*a*c*e*g*j*",
  984. "!a*jj*fff",
  985. "!a*jj*zzz",
  986. "a*jj*fff*",
  987. "*aa*jj*fff*",
  988. "!a*jj*zy*",
  989. nullptr
  990. };
  991. const char * const patternsLarge [] = {
  992. "!*a*zy*",
  993. "a*",
  994. "a*h*",
  995. "!a*jj*ab",
  996. "!a*jj*zy",
  997. "a*jj*fff*",
  998. "!a*jj*zy*",
  999. /* "!a*c*e*g*i*k*zy*", will completely destroy the performance*/
  1000. nullptr
  1001. };
  1002. class JlibWildMatchCore : public JlibWildMatchBase
  1003. {
  1004. CPPUNIT_TEST_SUITE(JlibWildMatchCore);
  1005. CPPUNIT_TEST(testWildMatch);
  1006. CPPUNIT_TEST_SUITE_END();
  1007. public:
  1008. void testWildMatch()
  1009. {
  1010. testSet(10, patterns10, false);
  1011. testSet(100, patterns100, false);
  1012. testSet(1000, patternsLarge, false);
  1013. }
  1014. };
  1015. CPPUNIT_TEST_SUITE_REGISTRATION(JlibWildMatchCore);
  1016. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibWildMatchCore, "JlibWildMatchCore");
  1017. class JlibWildMatchTiming : public JlibWildMatchBase
  1018. {
  1019. CPPUNIT_TEST_SUITE(JlibWildMatchTiming);
  1020. CPPUNIT_TEST(testWildMatch);
  1021. CPPUNIT_TEST_SUITE_END();
  1022. public:
  1023. void testWildMatch()
  1024. {
  1025. testSet(10000, patternsLarge, true);
  1026. testSet(100000, patternsLarge, true);
  1027. testSet(1000000, patternsLarge, true);
  1028. }
  1029. };
  1030. CPPUNIT_TEST_SUITE_REGISTRATION(JlibWildMatchTiming);
  1031. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibWildMatchTiming, "JlibWildMatchTiming");
  1032. const EnumMapping mapping[] = {
  1033. { 1, "one" },
  1034. { 3, "three" },
  1035. { 5, "five" },
  1036. {0, nullptr }
  1037. };
  1038. const char * strings[] = { "zero", "one", "two", "three", "four", nullptr };
  1039. class JlibMapping : public CppUnit::TestFixture
  1040. {
  1041. CPPUNIT_TEST_SUITE(JlibMapping);
  1042. CPPUNIT_TEST(testEnum);
  1043. CPPUNIT_TEST(testMatch);
  1044. CPPUNIT_TEST_SUITE_END();
  1045. public:
  1046. void testEnum()
  1047. {
  1048. CPPUNIT_ASSERT(streq("one", getEnumText(1, mapping)));
  1049. CPPUNIT_ASSERT(streq("three", getEnumText(3, mapping)));
  1050. CPPUNIT_ASSERT(streq("five", getEnumText(5, mapping)));
  1051. CPPUNIT_ASSERT(streq("two", getEnumText(2, mapping, "two")));
  1052. CPPUNIT_ASSERT(!getEnumText(2, mapping, nullptr));
  1053. CPPUNIT_ASSERT_EQUAL(1, getEnum("one", mapping));
  1054. CPPUNIT_ASSERT_EQUAL(3, getEnum("three", mapping));
  1055. CPPUNIT_ASSERT_EQUAL(5, getEnum("five", mapping));
  1056. CPPUNIT_ASSERT_EQUAL(99, getEnum("seven", mapping, 99));
  1057. }
  1058. void testMatch()
  1059. {
  1060. CPPUNIT_ASSERT_EQUAL(0U, matchString("zero", strings));
  1061. CPPUNIT_ASSERT_EQUAL(1U, matchString("one", strings));
  1062. CPPUNIT_ASSERT_EQUAL(4U, matchString("four", strings));
  1063. CPPUNIT_ASSERT_EQUAL(UINT_MAX, matchString("ten", strings));
  1064. }
  1065. };
  1066. CPPUNIT_TEST_SUITE_REGISTRATION(JlibMapping);
  1067. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibMapping, "JlibMapping");
  1068. class JlibIPTTest : public CppUnit::TestFixture
  1069. {
  1070. CPPUNIT_TEST_SUITE(JlibIPTTest);
  1071. CPPUNIT_TEST(test);
  1072. CPPUNIT_TEST_SUITE_END();
  1073. public:
  1074. void test()
  1075. {
  1076. Owned<IPropertyTree> testTree = createPTreeFromXMLString(
  1077. "<cpptest attr1='attrval1' attr2='attrval2'>"
  1078. " <sub1 subattr1='sav1'>sub1val</sub1>"
  1079. " <sub2 subattr2='sav2'>sub2val</sub2>"
  1080. " <subX subattr3='sav3'>subXval</subX>"
  1081. " <item a='1' b='2' c='3' d='4'/>"
  1082. " <item a='2'/>"
  1083. " <item a='3'/>"
  1084. " <array>"
  1085. " <valX>x</valX>"
  1086. " <valX>x</valX>"
  1087. " <valY>y</valY>"
  1088. " <valY>y</valY>"
  1089. " <valZ>z</valZ>"
  1090. " </array>"
  1091. " <binprop bin='1' xsi:type='SOAP-ENC:base64'>CwAAAA==</binprop>"
  1092. "cpptestval"
  1093. "</cpptest>");
  1094. MemoryBuffer mb;
  1095. mb.reserveTruncate(4*1024+1); // Must be > PTREE_COMPRESS_THRESHOLD (see top of jptree.cpp)
  1096. testTree->addProp("binprop/subbinprop", "nonbinval1");
  1097. testTree->addPropBin("binprop/subbinprop", mb.length(), mb.toByteArray());
  1098. testTree->addProp("binprop/subbinprop", "nonbinval2");
  1099. testTree->addPropBin("binprop/subbinprop", mb.length(), mb.toByteArray());
  1100. // test some sets in prep. for 'get' tests
  1101. CPPUNIT_ASSERT(testTree->renameProp("subX", "subY"));
  1102. IPropertyTree *subY = testTree->queryPropTree("subY");
  1103. CPPUNIT_ASSERT(testTree->renameTree(subY, "sub3"));
  1104. IPropertyTree *subtest = testTree->setPropTree("subtest");
  1105. subtest = testTree->addPropTree("subtest", createPTree());
  1106. CPPUNIT_ASSERT(subtest != nullptr);
  1107. subtest = testTree->queryPropTree("subtest[2]");
  1108. CPPUNIT_ASSERT(subtest != nullptr);
  1109. subtest->setProp("str", "str1");
  1110. subtest->addProp("str", "str2");
  1111. subtest->appendProp("str[2]", "-more");
  1112. subtest->setPropBool("bool", true);
  1113. subtest->addPropBool("bool", false);
  1114. subtest->setPropInt("int", 1);
  1115. subtest->addPropInt("int", 2);
  1116. subtest->setPropInt64("int64", 1);
  1117. subtest->addPropInt64("int64", 2);
  1118. mb.clear().append("binstr1");
  1119. subtest->setPropBin("bin", mb.length(), mb.toByteArray());
  1120. mb.clear().append("binstr2");
  1121. subtest->addPropBin("bin", mb.length(), mb.toByteArray());
  1122. mb.clear().append("-more");
  1123. subtest->appendPropBin("bin[1]", mb.length(), mb.toByteArray());
  1124. // position insertion.
  1125. testTree->addProp("newprop", "v1");
  1126. testTree->addProp("newprop", "v2");
  1127. testTree->addProp("newprop[2]", "v3");
  1128. CPPUNIT_ASSERT(streq("v3", testTree->queryProp("newprop[2]")));
  1129. CPPUNIT_ASSERT(testTree->hasProp("sub1"));
  1130. CPPUNIT_ASSERT(testTree->hasProp("sub1/@subattr1"));
  1131. CPPUNIT_ASSERT(testTree->hasProp("sub2/@subattr2"));
  1132. CPPUNIT_ASSERT(testTree->hasProp("@attr1"));
  1133. CPPUNIT_ASSERT(!testTree->isBinary("@attr1"));
  1134. CPPUNIT_ASSERT(!testTree->isBinary("sub1"));
  1135. CPPUNIT_ASSERT(testTree->isBinary("binprop"));
  1136. CPPUNIT_ASSERT(!testTree->isCompressed("binprop"));
  1137. CPPUNIT_ASSERT(!testTree->isBinary("binprop/subbinprop[1]"));
  1138. CPPUNIT_ASSERT(testTree->isBinary("binprop/subbinprop[2]"));
  1139. CPPUNIT_ASSERT(!testTree->isCompressed("binprop/subbinprop[3]"));
  1140. CPPUNIT_ASSERT(testTree->isCompressed("binprop/subbinprop[4]"));
  1141. // testing if subX was renamed correctly
  1142. CPPUNIT_ASSERT(!testTree->hasProp("subX"));
  1143. CPPUNIT_ASSERT(!testTree->hasProp("subY"));
  1144. CPPUNIT_ASSERT(testTree->hasProp("sub3"));
  1145. StringBuffer astr;
  1146. CPPUNIT_ASSERT(testTree->getProp("sub1", astr));
  1147. CPPUNIT_ASSERT(streq("sub1val", astr.str()));
  1148. CPPUNIT_ASSERT(streq("sub2val", testTree->queryProp("sub2")));
  1149. subtest = testTree->queryPropTree("subtest[2]");
  1150. CPPUNIT_ASSERT(subtest != nullptr);
  1151. CPPUNIT_ASSERT(subtest->getPropBool("bool[1]"));
  1152. CPPUNIT_ASSERT(!subtest->getPropBool("bool[2]"));
  1153. CPPUNIT_ASSERT(1 == subtest->getPropInt("int[1]"));
  1154. CPPUNIT_ASSERT(2 == subtest->getPropInt("int[2]"));
  1155. CPPUNIT_ASSERT(1 == subtest->getPropInt64("int64[1]"));
  1156. CPPUNIT_ASSERT(2 == subtest->getPropInt64("int64[2]"));
  1157. subtest->getPropBin("bin[1]", mb.clear());
  1158. const char *ptr = (const char *)mb.toByteArray();
  1159. CPPUNIT_ASSERT(streq("binstr1", ptr)); // NB: null terminator was added at set time.
  1160. CPPUNIT_ASSERT(streq("-more", ptr+strlen("binstr1")+1)); // NB: null terminator was added at set time.
  1161. subtest->getPropBin("bin[2]", mb.clear());
  1162. CPPUNIT_ASSERT(streq("binstr2", mb.toByteArray())); // NB: null terminator was added at set time.
  1163. CPPUNIT_ASSERT(testTree->hasProp("subtest/bin[2]"));
  1164. CPPUNIT_ASSERT(testTree->removeProp("subtest/bin[2]"));
  1165. CPPUNIT_ASSERT(!testTree->hasProp("subtest/bin[2]"));
  1166. CPPUNIT_ASSERT(testTree->hasProp("subtest"));
  1167. CPPUNIT_ASSERT(testTree->removeTree(subtest)); // this is subtest[2]
  1168. subtest = testTree->queryPropTree("subtest"); // now just 1
  1169. CPPUNIT_ASSERT(testTree->removeTree(subtest));
  1170. CPPUNIT_ASSERT(!testTree->hasProp("subtest"));
  1171. IPropertyTree *item3 = testTree->queryPropTree("item[@a='3']");
  1172. CPPUNIT_ASSERT(nullptr != item3);
  1173. CPPUNIT_ASSERT(2 == testTree->queryChildIndex(item3));
  1174. CPPUNIT_ASSERT(streq("item", item3->queryName()));
  1175. Owned<IPropertyTreeIterator> iter = testTree->getElements("item");
  1176. unsigned a=1;
  1177. ForEach(*iter)
  1178. {
  1179. CPPUNIT_ASSERT(a == iter->query().getPropInt("@a"));
  1180. ++a;
  1181. }
  1182. Owned<IAttributeIterator> attrIter = testTree->queryPropTree("item[1]")->getAttributes();
  1183. CPPUNIT_ASSERT(4 == attrIter->count());
  1184. unsigned i = 0;
  1185. ForEach(*attrIter)
  1186. {
  1187. const char *name = attrIter->queryName();
  1188. const char *val = attrIter->queryValue();
  1189. CPPUNIT_ASSERT('a'+i == *(name+1));
  1190. CPPUNIT_ASSERT('1'+i == *val);
  1191. ++i;
  1192. }
  1193. IPropertyTree *array = testTree->queryPropTree("array");
  1194. CPPUNIT_ASSERT(array != nullptr);
  1195. CPPUNIT_ASSERT(array->hasChildren());
  1196. CPPUNIT_ASSERT(3 == array->numUniq());
  1197. CPPUNIT_ASSERT(5 == array->numChildren());
  1198. CPPUNIT_ASSERT(!testTree->isCaseInsensitive());
  1199. CPPUNIT_ASSERT(3 == testTree->getCount("sub*"));
  1200. }
  1201. };
  1202. CPPUNIT_TEST_SUITE_REGISTRATION(JlibIPTTest);
  1203. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibIPTTest, "JlibIPTTest");
  1204. #include "jdebug.hpp"
  1205. #include "jmutex.hpp"
  1206. class AtomicTimingTest : public CppUnit::TestFixture
  1207. {
  1208. CPPUNIT_TEST_SUITE(AtomicTimingTest);
  1209. CPPUNIT_TEST(runAllTests);
  1210. CPPUNIT_TEST_SUITE_END();
  1211. public:
  1212. class CasCounter
  1213. {
  1214. public:
  1215. CasCounter() = default;
  1216. CasCounter(unsigned __int64 _value) : value{_value} {}
  1217. operator unsigned __int64() { return value; }
  1218. unsigned __int64 operator = (unsigned __int64 _value)
  1219. {
  1220. value = _value;
  1221. return _value;
  1222. }
  1223. unsigned __int64 operator ++(int)
  1224. {
  1225. unsigned __int64 expected = value.load();
  1226. while (!value.compare_exchange_weak(expected, expected + 1))
  1227. {
  1228. }
  1229. return expected+1;
  1230. }
  1231. std::atomic<unsigned __int64> value = { 0 };
  1232. };
  1233. template <typename LOCK, typename BLOCK, typename COUNTER, unsigned NUMVALUES, unsigned NUMLOCKS>
  1234. class LockTester
  1235. {
  1236. public:
  1237. LockTester()
  1238. {
  1239. value1 = 0;
  1240. }
  1241. class LockTestThread : public Thread
  1242. {
  1243. public:
  1244. LockTestThread(Semaphore & _startSem, Semaphore & _endSem, LOCK & _lock1, COUNTER & _value1, LOCK & _lock2, COUNTER * _extraValues, unsigned _numIterations)
  1245. : startSem(_startSem), endSem(_endSem),
  1246. lock1(_lock1), value1(_value1),
  1247. lock2(_lock2), extraValues(_extraValues),
  1248. numIterations(_numIterations)
  1249. {
  1250. }
  1251. virtual void execute()
  1252. {
  1253. {
  1254. BLOCK block(lock1);
  1255. value1++;
  1256. if (NUMVALUES >= 2)
  1257. extraValues[1]++;
  1258. if (NUMVALUES >= 3)
  1259. extraValues[2]++;
  1260. if (NUMVALUES >= 4)
  1261. extraValues[3]++;
  1262. if (NUMVALUES >= 5)
  1263. extraValues[4]++;
  1264. }
  1265. if (NUMLOCKS == 2)
  1266. {
  1267. BLOCK block(lock2);
  1268. extraValues[1]++;
  1269. }
  1270. }
  1271. virtual int run()
  1272. {
  1273. startSem.wait();
  1274. for (unsigned i = 0; i < numIterations; i++)
  1275. execute();
  1276. endSem.signal();
  1277. return 0;
  1278. }
  1279. protected:
  1280. Semaphore & startSem;
  1281. Semaphore & endSem;
  1282. LOCK & lock1;
  1283. LOCK & lock2;
  1284. COUNTER & value1;
  1285. COUNTER * extraValues;
  1286. const unsigned numIterations;
  1287. };
  1288. unsigned __int64 run(const char * title, unsigned numThreads, unsigned numIterations)
  1289. {
  1290. value1 = 0;
  1291. for (unsigned ix = 1; ix < NUMVALUES; ix++)
  1292. extraValues[ix] = 0;
  1293. for (unsigned i = 0; i < numThreads; i++)
  1294. {
  1295. LockTestThread * next = new LockTestThread(startSem, endSem, lock, value1, lock, extraValues, numIterations);
  1296. threads.append(*next);
  1297. next->start();
  1298. }
  1299. cycle_t startCycles = get_cycles_now();
  1300. startSem.signal(numThreads);
  1301. for (unsigned i2 = 0; i2 < numThreads; i2++)
  1302. endSem.wait();
  1303. cycle_t endCycles = get_cycles_now();
  1304. unsigned __int64 expected = (unsigned __int64)numIterations * numThreads;
  1305. unsigned __int64 averageTime = cycle_to_nanosec(endCycles - startCycles) / (numIterations * numThreads);
  1306. printf("%s@%u/%u threads(%u) %" I64F "uns/iteration lost(%" I64F "d)\n", title, NUMVALUES, NUMLOCKS, numThreads, averageTime, expected - value1);
  1307. for (unsigned i3 = 0; i3 < numThreads; i3++)
  1308. threads.item(i3).join();
  1309. return averageTime;
  1310. }
  1311. protected:
  1312. CIArrayOf<LockTestThread> threads;
  1313. Semaphore startSem;
  1314. Semaphore endSem;
  1315. LOCK lock;
  1316. COUNTER value1;
  1317. COUNTER extraValues[NUMVALUES];
  1318. };
  1319. #define DO_TEST(LOCK, CLOCK, COUNTER, NUMVALUES, NUMLOCKS) \
  1320. { \
  1321. const char * title = #LOCK "," #COUNTER;\
  1322. LockTester<LOCK, CLOCK, COUNTER, NUMVALUES, NUMLOCKS> tester;\
  1323. uncontendedTimes.append(tester.run(title, 1, numIterations));\
  1324. minorTimes.append(tester.run(title, 2, numIterations));\
  1325. typicalTimes.append(tester.run(title, numCores / 2, numIterations));\
  1326. tester.run(title, numCores, numIterations);\
  1327. tester.run(title, numCores + 1, numIterations);\
  1328. contendedTimes.append(tester.run(title, numCores * 2, numIterations));\
  1329. }
  1330. //Use to common out a test
  1331. #define XDO_TEST(LOCK, CLOCK, COUNTER, NUMVALUES, NUMLOCKS) \
  1332. { \
  1333. uncontendedTimes.append(0);\
  1334. minorTimes.append(0);\
  1335. typicalTimes.append(0);\
  1336. contendedTimes.append(0);\
  1337. }
  1338. class Null
  1339. {};
  1340. const unsigned numIterations = 1000000;
  1341. const unsigned numCores = getAffinityCpus();
  1342. void runAllTests()
  1343. {
  1344. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 1, 1);
  1345. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 2, 1);
  1346. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 5, 1);
  1347. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 1, 2);
  1348. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 1, 1);
  1349. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 2, 1);
  1350. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 5, 1);
  1351. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 1, 2);
  1352. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 1, 1);
  1353. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 2, 1);
  1354. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 5, 1);
  1355. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 1, 2);
  1356. DO_TEST(Null, Null, RelaxedAtomic<unsigned __int64>, 1, 1);
  1357. DO_TEST(Null, Null, RelaxedAtomic<unsigned __int64>, 5, 1);
  1358. DO_TEST(Null, Null, CasCounter, 1, 1);
  1359. DO_TEST(Null, Null, CasCounter, 5, 1);
  1360. DO_TEST(Null, Null, unsigned __int64, 1, 1);
  1361. DO_TEST(Null, Null, unsigned __int64, 2, 1);
  1362. DO_TEST(Null, Null, unsigned __int64, 5, 1);
  1363. //Read locks will fail to prevent values being lost, but the timings are useful in comparison with CriticalSection
  1364. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 1, 1);
  1365. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 2, 1);
  1366. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 5, 1);
  1367. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 1, 2);
  1368. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 1, 1);
  1369. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 2, 1);
  1370. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 5, 1);
  1371. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 1, 2);
  1372. printf("Summary\n");
  1373. summariseTimings("Uncontended", uncontendedTimes);
  1374. summariseTimings("Minor", minorTimes);
  1375. summariseTimings("Typical", typicalTimes);
  1376. summariseTimings("Over", contendedTimes);
  1377. }
  1378. void summariseTimings(const char * option, UInt64Array & times)
  1379. {
  1380. printf("%11s 1x: cs(%3" I64F "u) spin(%3" I64F "u) atomic(%3" I64F "u) ratomic(%3" I64F "u) cas(%3" I64F "u) rd(%3" I64F "u) wr(%3" I64F "u) "
  1381. "5x: cs(%3" I64F "u) spin(%3" I64F "u) atomic(%3" I64F "u) ratomic(%3" I64F "u) cas(%3" I64F "u) rd(%3" I64F "u) wr(%3" I64F "u)\n", option,
  1382. times.item(0), times.item(4), times.item(8), times.item(12), times.item(14), times.item(19), times.item(23),
  1383. times.item(2), times.item(6), times.item(10), times.item(13), times.item(15), times.item(21), times.item(25));
  1384. }
  1385. private:
  1386. UInt64Array uncontendedTimes;
  1387. UInt64Array minorTimes;
  1388. UInt64Array typicalTimes;
  1389. UInt64Array contendedTimes;
  1390. };
  1391. CPPUNIT_TEST_SUITE_REGISTRATION(AtomicTimingTest);
  1392. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AtomicTimingTest, "AtomicTimingTest");
  1393. #endif // _USE_CPPUNIT