Oh no! Some styles failed to load. 😵 Please try reloading this page
Menu â–¾ â–´

[r138]: / core / App.cpp  Maximize  Restore  History

Download this file

896 lines (683 with data), 26.9 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
/* App.cpp -- (C) Mark Rodenkirch, January 2018
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#include <time.h>
#include <vector>
#include <stdarg.h>
#include "App.h"
#include "Clock.h"
#include "../x86_asm/fpu-asm-x86.h"
#include "../x86_asm/sse-asm-x86.h"
// Do not change this as some parts of the framework assume that this is set to 60 seconds
#define REPORT_SECONDS 60
#define REPORT_STRFTIME_FORMAT "ETC %Y-%m-%d %H:%M"
#define LOG_STRFTIME_FORMAT "%Y-%m-%d %H:%M:%S"
App::App(void)
{
ii_SavedFpuMode = fpu_mod_init();
ii_SavedSseMode = sse_mod_init();
il_TotalClockTime = 0;
il_WorkerClockTime = 0;
il_InitUS = Clock::GetCurrentMicrosecond();
ii_CpuWorkerCount = 0;
ii_GpuWorkerCount = 0;
ip_Console = new SharedMemoryItem("console");
ip_AppStatus = new SharedMemoryItem("appstatus");
ip_SievingStatus = new SharedMemoryItem("sievestatus");
ip_NeedToRebuild = new SharedMemoryItem("rebuild");
icot_LastConsoleOutputType = COT_OTHER;
ip_AppStatus->SetValueNoLock(AS_INITIALIZING);
ip_SievingStatus->SetValueNoLock(SS_NOT_STARTED);
// The application cannot exceeds these max values
il_AppMinPrime = PMIN_MIN;
il_AppMaxPrime = PMAX_MAX_62BIT;
il_MinPrime = il_AppMinPrime;
il_MaxPrime = il_AppMaxPrime;
il_MaxPrimeForSingleWorker = 0;
il_LargestPrimeSieved = 0;
ii_CpuWorkSize = 1000000;
// We won't know this until we create a kernel in the GPU
il_MinGpuPrime = 0;
ib_HaveCreatedWorkers = false;
ib_SetMinPrimeFromCommandLine = false;
ip_Workers = (Worker **) xmalloc((MAX_WORKERS + 1) * sizeof(Worker *));
#ifdef HAVE_GPU_WORKERS
ip_Device = new Device();
ii_GpuWorkGroupSize = 0;
ii_GpuWorkGroups = 10;
#endif
}
App::~App(void)
{
DeleteWorkers();
xfree(ip_Workers);
delete ip_Console;
sse_mod_fini(ii_SavedSseMode);
fpu_mod_fini(ii_SavedFpuMode);
}
void App::Banner(void)
{
printf("%s\n", is_Banner.c_str());
}
void App::ParentHelp(void)
{
char maxPrime[30];
ConvertNumberToShortString(il_AppMaxPrime, (char *) maxPrime);
printf("-p --pmin=P0 sieve start: P0 < p (default %" PRIu64")\n", il_AppMinPrime);
printf("-P --pmax=P1 sieve end: p < P1 (default %s)\n", maxPrime);
printf("-w --worksize=w primes per chunk of work (default %u)\n", ii_CpuWorkSize);
printf("-W --workers=W start W workers (default %u)\n", ii_CpuWorkerCount);
#ifdef HAVE_GPU_WORKERS
printf("-g --gpuworkgroups=g work groups per call to GPU (default %u)\n", ii_GpuWorkGroups);
printf("-G --gpuworkers=G start G GPU workers (default %u)\n", ii_GpuWorkerCount);
ip_Device->Help();
#endif
}
void App::ParentAddCommandLineOptions(string &shortOpts, struct option *longOpts)
{
shortOpts += "p:P:w:W:";
AppendLongOpt(longOpts, "pmin", required_argument, 0, 'p');
AppendLongOpt(longOpts, "pmax", required_argument, 0, 'P');
AppendLongOpt(longOpts, "worksize", required_argument, 0, 'w');
AppendLongOpt(longOpts, "workers", required_argument, 0, 'W');
#ifdef HAVE_GPU_WORKERS
shortOpts += "g:G:";
AppendLongOpt(longOpts, "gpuworkgroups", required_argument, 0, 'g');
AppendLongOpt(longOpts, "gpuworkers", required_argument, 0, 'G');
ip_Device->AddCommandLineOptions(shortOpts, longOpts);
#endif
}
// Returns:
// 0 if the option is OK
// -1 if the argument is invalid
// -2 if the argument is out of range
// 99 if the argument is not supported by this module
parse_t App::ParentParseOption(int opt, char *arg, const char *source)
{
parse_t status = P_UNSUPPORTED;
uint64_t minPrime;
#ifdef HAVE_GPU_WORKERS
status = ip_Device->ParseOption(opt, arg, source);
if (status != P_UNSUPPORTED)
return status;
#endif
switch (opt)
{
case 'p':
status = Parser::Parse(arg, il_AppMinPrime, il_AppMaxPrime-1, minPrime);
SetMinPrime(minPrime);
ib_SetMinPrimeFromCommandLine = true;
break;
case 'P':
status = Parser::Parse(arg, il_AppMinPrime+1, il_AppMaxPrime, il_MaxPrime);
break;
case 'w':
status = Parser::Parse(arg, 10, 1000000000, ii_CpuWorkSize);
break;
#ifdef HAVE_GPU_WORKERS
case 'W':
status = Parser::Parse(arg, 0, MAX_WORKERS, ii_CpuWorkerCount);
break;
case 'g':
status = Parser::Parse(arg, 1, 1000000, ii_GpuWorkGroups);
break;
case 'G':
status = Parser::Parse(arg, 0, MAX_WORKERS, ii_GpuWorkerCount);
break;
#else
case 'W':
status = Parser::Parse(arg, 1, MAX_WORKERS, ii_CpuWorkerCount);
break;
#endif
}
return status;
}
void App::ParentValidateOptions(void)
{
if (ii_CpuWorkerCount + ii_GpuWorkerCount > MAX_WORKERS)
FatalError("Too many workers are configured. The limit is %u", MAX_WORKERS);
if (ii_CpuWorkerCount + ii_GpuWorkerCount == 0)
{
#ifdef HAVE_GPU_WORKERS
ii_GpuWorkerCount = 1;
#else
ii_CpuWorkerCount = 1;
#endif
}
// Ensure that the number of primes is divisble by 32
// Although not required by all CPU sieves, many of them optimize
// with groups of 4, 16, or 32 primes.
while (ii_CpuWorkSize & 0x10)
ii_CpuWorkSize++;
if (il_MinPrime >= il_MaxPrime)
FatalError("pmin must be less than pmax");
ii_TotalWorkerCount = ii_CpuWorkerCount + ii_GpuWorkerCount;
#ifdef HAVE_GPU_WORKERS
ip_Device->Validate();
#endif
}
void App::ConvertNumberToShortString(uint64_t value, char *buffer)
{
if (value == PMAX_MAX_52BIT)
{
strcpy(buffer, "2^52");
return;
}
if (value == PMAX_MAX_62BIT)
{
strcpy(buffer, "2^62");
return;
}
if (value % 1000 != 0)
{
sprintf(buffer, "%" PRIu64"", value);
return;
}
// Convert to scientific notation
uint32_t e = 0;
while (value % 10 == 0)
{
value /= 10;
e++;
}
sprintf(buffer, "%" PRIu64"e%u", value, e);
}
void App::SetLogFileName(string logFileName)
{
is_LogFileName = logFileName;
FILE *fPtr = fopen(is_LogFileName.c_str(), "a");
if (!fPtr)
FatalError("Cannot open log file <%s>", is_LogFileName.c_str());
fclose(fPtr);
}
void App::WriteToLog(const char *fmt, ...)
{
va_list args;
time_t theTime = time(NULL);
char timeBuffer[32];
if (!strftime(timeBuffer, sizeof(timeBuffer), LOG_STRFTIME_FORMAT, localtime(&theTime)))
timeBuffer[0] = '\0';
ip_Console->Lock();
FILE *fPtr = fopen(is_LogFileName.c_str(), "a");
if (!fPtr)
FatalError("Cannot open log file <%s>", is_LogFileName.c_str());
fprintf(fPtr, "%s: ", timeBuffer);
va_start(args, fmt);
vfprintf(fPtr, fmt, args);
va_end(args);
fprintf(fPtr, "\n");
fclose(fPtr);
ip_Console->Release();
}
void App::WriteToConsole(cotype_t consoleOutputType, const char *fmt, ...)
{
va_list args;
ip_Console->Lock();
// If the previous message was a status message and this message is not the
// same type of status message, trigger a line feed.
if (icot_LastConsoleOutputType != COT_OTHER && icot_LastConsoleOutputType != consoleOutputType)
printf("\n");
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
// For some outputs to the console we want to trigger a line feed. An example
// of this would be an important result discovered by the application. For
// other outputs we just want to trigger a carriage return so that the next
// line can overwrite the line we just output to the console. An example of
// this would be a status message that indicates progress.
if (consoleOutputType == COT_OTHER)
printf("\n");
else
printf("\r");
fflush(stdout);
icot_LastConsoleOutputType = consoleOutputType;
ip_Console->Release();
}
void App::StopWorkers(void)
{
int64_t count = 1;
int64_t iter = 0;
// This tells the Workers to stop as soon as possible.
ip_SievingStatus->SetValueNoLock(SS_DONE);
count = 1;
while (count)
{
CheckReportStatus();
Sleep(100);
count = 0;
for (uint32_t ii=0; ii<=ii_TotalWorkerCount; ii++)
{
// ip_Worker[0] is the special CPU worker (if we need one)
if (ii == 0 && ip_Workers[0] == NULL)
continue;
if (!ip_Workers[ii]->IsStopped())
count++;
}
if (count && ++iter > 60000)
{
WriteToConsole(COT_OTHER, "%d workers didn't stop after 10 minutes", (int32_t) count);
exit(0);
}
}
}
void App::Interrupt(void)
{
ip_AppStatus->SetValueNoLock(AS_INTERRUPTED);
uint64_t maxPrime = (il_LargestPrimeSieved > il_MaxPrime ? il_MaxPrime : il_LargestPrimeSieved);
WriteToConsole(COT_OTHER, "CTRL-C accepted. Threads will stop after sieving to %" PRIu64"", maxPrime);
}
void App::SetMinPrime(uint64_t minPrime)
{
if (ib_SetMinPrimeFromCommandLine)
return;
il_MinPrime = minPrime;
}
// Overrice the max prime to be sieved so that we can guarantee
// that all remaining terms are prime.
void App::SetMaxPrime(uint64_t maxPrime, const char *why)
{
WriteToConsole(COT_OTHER, "Changing p_max to %" PRIu64". %s.", maxPrime, why);
il_MaxPrime = maxPrime;
}
void App::Run(void)
{
bool isDone;
ValidateOptions();
ii_SavedFpuMode = fpu_mod_init();
ii_SavedSseMode = sse_mod_init();
do
{
// This gives applications a chance to change any configurations prior to sieving.
PreSieveHook();
CreateWorkers(il_MinPrime);
#ifdef HAVE_GPU_WORKERS
if (ii_GpuWorkerCount > 0)
{
if (ii_GpuWorkGroupSize == 0)
FatalError("could not compute optimal size of GPU work group");
WriteToConsole(COT_OTHER, "GPU primes per worker is %u", GetGpuWorkSize());
}
#endif
Sieve();
isDone = PostSieveHook();
if (!isDone)
DeleteWorkers();
} while (!isDone);
}
void App::Sieve(void)
{
uint32_t th;
uint64_t sieveStartUS;
bool useSingleThread;
LogStartSievingMessage();
ip_AppStatus->SetValueNoLock(AS_RUNNING);
ip_SievingStatus->SetValueNoLock(SS_SIEVING);
il_LargestPrimeSieved = il_MinPrime - 1;
il_StartSievingUS = Clock::GetCurrentMicrosecond();
it_StartTime = time(NULL);
it_ReportTime = it_StartTime + REPORT_SECONDS;
useSingleThread = (il_LargestPrimeSieved < il_MaxPrimeForSingleWorker);
while (il_LargestPrimeSieved < il_MaxPrime && IsRunning())
{
th = GetNextAvailableWorker(useSingleThread, il_LargestPrimeSieved);
// Stop if we couldn't get a worker. This should only happen if there is
// a problem with the application or if ip_AppStatus is not AS_RUNNING.
if (th == NO_WORKER)
break;
sieveStartUS = Clock::GetThreadMicroseconds();
il_LargestPrimeSieved = ip_Workers[th]->ProcessNextPrimeChunk(il_LargestPrimeSieved, il_MaxPrimeForSingleWorker);
il_TotalSieveUS += (Clock::GetThreadMicroseconds() - sieveStartUS);
// If we are using a single thread, then this will effectively block other Workers
// from getting work until both this Worker is done and the largest prime tested for
// this workr exceeds the max prime for a single CPU thread.
if (th == 0 || useSingleThread)
{
while (!ip_Workers[th]->IsWaitingForWork(false) && !ip_Workers[th]->IsStopped())
{
CheckReportStatus();
Sleep(10);
}
useSingleThread = (ip_Workers[th]->GetLargestPrimeTested() < il_MaxPrimeForSingleWorker);
}
}
Finish();
}
uint32_t App::GetNextAvailableWorker(bool useSingleThread, uint64_t &largestPrimeSieved)
{
uint32_t th;
uint32_t attempts = 0;
while (true)
{
attempts++;
// Return NO_WORKER to indicate that we are returning without selecting
// a worker as we want to stop processing.
if (!IsRunning())
return NO_WORKER;
// If rebuilding, then the largest prime tested might be smaller
// than the largest prime sieved so we have to update it.
if (IsRebuildNeeded())
largestPrimeSieved = PauseSievingAndRebuild();
CheckReportStatus();
for (th=0; th<=ii_TotalWorkerCount; th++)
{
// ip_Worker[0] is the special CPU worker (if we need one).
// It will only stop when we can switch to the other workers.
if (th == 0)
{
if (ip_Workers[0] == NULL)
continue;
if (ip_Workers[0]->IsStopped())
continue;
if (ip_Workers[0]->IsWaitingForWork(true))
return th;
continue;
}
if (ip_Workers[th]->IsGpuWorker())
{
if (useSingleThread)
continue;
if (largestPrimeSieved < il_MinGpuPrime)
continue;
}
if (ip_Workers[th]->IsWaitingForWork(true))
return th;
}
// If we didn't find one, sleep
Sleep(10);
}
}
uint64_t App::PauseSievingAndRebuild(void)
{
uint64_t largestPrimeTested;
StopWorkers();
// We can pass true because all workers are stopped which means that
// they have completed sieving their respective range of primes.
largestPrimeTested = GetLargestPrimeTested(true);
NotifyAppToRebuild(largestPrimeTested);
DeleteWorkers();
// Reset the sieving status since StopWorkers had changed to SS_DONE
ip_SievingStatus->SetValueNoLock(SS_SIEVING);
CreateWorkers(largestPrimeTested);
ResetFactorStats();
SetRebuildCompleted();
return largestPrimeTested;
}
void App::CheckReportStatus(void)
{
time_t theTime = time(NULL);
if (theTime > it_ReportTime)
{
ReportStatus();
it_ReportTime = theTime + REPORT_SECONDS;
}
}
void App::DeleteWorkers(void)
{
for (uint32_t ii=0; ii<=ii_TotalWorkerCount; ii++)
{
// ip_Worker[0] is the special CPU worker (if we need one)
if (ii == 0 && ip_Workers[0] == NULL)
continue;
ip_Workers[ii]->CleanUp();
delete ip_Workers[ii];
}
}
void App::CreateWorkers(uint64_t largestPrimeTested)
{
uint32_t w, th;
bool allWaiting = false;
ip_Workers[0] = NULL;
if (ii_CpuWorkerCount == 0 && largestPrimeTested < il_MinGpuPrime)
{
// Worker "0" is only created if all of the following conditions are met:
// no CPU workers specified
// the application supports GPU workers
// the next prime tested cannot be tested on a GPU
WriteToConsole(COT_OTHER, "Creating CPU worker to use until p >= %" PRIu64"", il_MinGpuPrime);
ip_Workers[0] = CreateWorker(0, false, largestPrimeTested);
}
th = 1;
// This will create the workers and start executing them
// Create the CPU workers first, then the GPU workers
for (w=0; w<ii_CpuWorkerCount; w++, th++)
ip_Workers[th] = CreateWorker(th, false, largestPrimeTested);
for (w=0; w<ii_GpuWorkerCount; w++, th++)
ip_Workers[th] = CreateWorker(th, true, largestPrimeTested);
ib_HaveCreatedWorkers = true;
// We can't start until all workers waiting for work
while (!allWaiting)
{
Sleep(10);
allWaiting = true;
for (th=0; th<=ii_TotalWorkerCount; th++)
{
// ip_Worker[0] is the special CPU worker (if we need one)
if (th == 0 && ip_Workers[0] == NULL)
continue;
if (!ip_Workers[th]->IsWaitingForWork(false))
allWaiting = false;
}
}
il_LastStatusReportUS = Clock::GetCurrentMicrosecond();
il_LastStatusPrimesTested = 0;
}
void App::Finish(void)
{
uint64_t largestPrimeTestedNoGaps, largestPrimeTested, primesTested;
uint64_t workerCpuUS;
uint64_t processCpuUS;
uint64_t elapsedTimeUS;
double cpuUtilization;
const char *finishMethod = (IsInterrupted() ? "interrupted" : "completed");
// This won't return until all workers have completed processing work assigned to them.
StopWorkers();
processCpuUS = Clock::GetProcessMicroseconds();
elapsedTimeUS = Clock::GetCurrentMicrosecond() - il_StartSievingUS;
GetWorkerStats(workerCpuUS, largestPrimeTestedNoGaps, largestPrimeTested, primesTested);
// Since all threads finished normally, there are no gaps thus we use largestPrimeTested.
WriteToConsole(COT_OTHER, "Sieve %s at p=%" PRIu64".", finishMethod, largestPrimeTested);
cpuUtilization = ((double) processCpuUS) / ((double) elapsedTimeUS);
#ifdef HAVE_GPU_WORKERS
uint64_t processGpuUS = ip_Device->GetGpuMicroseconds();
// This outputs statistics regarding CPU time, i.e. time the CPU (or cores) spent
// on this program, thus not including time spent working on other processes
WriteToConsole(COT_OTHER, "CPU time: %.2f sec. (%.2f sieving) (%.2f cores) GPU time: %.2f sec. ",
processCpuUS/1000000.0,
il_TotalSieveUS/1000000.0,
cpuUtilization,
processGpuUS/1000000.0);
#else
// This outputs statistics regarding CPU time, i.e. time the CPU (or cores) spent
// on this program, thus not including time spent working on other processes
WriteToConsole(COT_OTHER, "CPU time: %.2f sec. (%.2f sieving) (%.2f cores)",
processCpuUS/1000000.0,
il_TotalSieveUS/1000000.0,
cpuUtilization);
#endif
Finish(finishMethod, elapsedTimeUS, largestPrimeTested, primesTested);
ip_AppStatus->SetValueNoLock(AS_FINISHED);
}
void App::ReportStatus(void)
{
double percentDone;
bool havePercentDone;
double primeRate;
double cpuUtilization;
uint32_t primePrecision;
const char *primeRateUnit;
struct tm *finish_tm;
char childStats[200];
char finishTimeBuffer[32];
uint64_t currentUS, workerCpuUS;
uint64_t processCpuUS, elapsedTimeUS;
uint64_t largestPrimeTestedNoGaps, largestPrimeTested, primesTested;
time_t finish_date;
currentUS = Clock::GetCurrentMicrosecond();
processCpuUS = Clock::GetProcessMicroseconds();
elapsedTimeUS = Clock::GetCurrentMicrosecond() - il_StartSievingUS;
GetWorkerStats(workerCpuUS, largestPrimeTestedNoGaps, largestPrimeTested, primesTested);
#ifdef HAVE_GPU_WORKERS
// Treat time spent in GPU as if spent in CPU
cpuUtilization = ((double) processCpuUS + ip_Device->GetGpuMicroseconds()) / ((double) elapsedTimeUS);
#else
cpuUtilization = ((double) processCpuUS) / ((double) elapsedTimeUS);
#endif
GetReportStats(childStats, cpuUtilization);
// Compute the percentage of the range we have completed
if (largestPrimeTestedNoGaps == 0)
havePercentDone = false;
else
{
havePercentDone = true;
if (IsInterrupted())
percentDone = (double)(largestPrimeTestedNoGaps-il_MinPrime)/(il_LargestPrimeSieved-il_MinPrime);
else
{
percentDone = (double)(largestPrimeTestedNoGaps-il_MinPrime)/(il_MaxPrime-il_MinPrime);
if (percentDone < 1.0 && il_MaxPrime == il_AppMaxPrime)
havePercentDone = false;
}
}
// Compute how many primes are tested per second since the last report
primeRate = (double)(primesTested-il_LastStatusPrimesTested)/(currentUS-il_LastStatusReportUS);
primeRateUnit = "M";
if (primeRate < 1.0) primeRate *= 1000.0, primeRateUnit = "K";
if (primeRate < 1.0) primeRate *= 1000.0, primeRateUnit = "";
primePrecision = 0;
if (primeRate < 1000.0) primePrecision = 1;
if (primeRate < 100.0) primePrecision = 2;
if (primeRate < 10.0) primePrecision = 3;
// Calculate ETC.
finishTimeBuffer[0] = '\0';
if (havePercentDone && percentDone > 0.0)
{
finish_date = (time_t) (it_StartTime + (time(NULL)-it_StartTime)/percentDone);
finish_tm = localtime(&finish_date);
if (!finish_tm || !strftime(finishTimeBuffer, sizeof(finishTimeBuffer), REPORT_STRFTIME_FORMAT, finish_tm))
finishTimeBuffer[0] = '\0';
}
if (strlen(childStats) > 0)
{
if (!havePercentDone)
WriteToConsole(COT_SIEVE, " p=%" PRIu64", %.*f%s p/sec, %s ",
largestPrimeTestedNoGaps, primePrecision, primeRate, primeRateUnit, childStats);
else
WriteToConsole(COT_SIEVE, " p=%" PRIu64", %.*f%s p/sec, %s, %.1f%% done. %s ",
largestPrimeTestedNoGaps, primePrecision, primeRate, primeRateUnit,
childStats, 100.0*percentDone, finishTimeBuffer);
}
else
{
if (!havePercentDone)
WriteToConsole(COT_SIEVE, " p=%" PRIu64", %.*f%s p/sec ",
largestPrimeTestedNoGaps, primePrecision, primeRate, primeRateUnit);
else
WriteToConsole(COT_SIEVE, " p=%" PRIu64", %.*f%s p/sec, %.1f%% done. %s ",
largestPrimeTestedNoGaps, primePrecision, primeRate, primeRateUnit,
100.0*percentDone, finishTimeBuffer);
}
il_LastStatusReportUS = currentUS;
il_LastStatusPrimesTested = primesTested;
}
// When the program finishes, then the largest prime tested across all workers
// tells us that all primes below that value have been tested. This is because
// none of the workers can be terminated while working on a chunk of primes.
// If we are still sieving, the largest prime tested might not be correct
// as threads will finish out of sequence, but that is okay.
void App::GetWorkerStats(uint64_t &workerCpuUS, uint64_t &largestPrimeTestedNoGaps, uint64_t &largestPrimeTested, uint64_t &primesTested)
{
uint64_t workerLargestPrimeTested;
workerCpuUS = 0;
primesTested = 0;
largestPrimeTested = 0;
largestPrimeTestedNoGaps = PMAX_MAX_62BIT;
#ifdef HAVE_GPU_WORKERS
// Treat time spent in GPU as if spent in CPU
workerCpuUS += ip_Device->GetGpuMicroseconds();
#endif
for (uint32_t ii=0; ii<=ii_TotalWorkerCount; ii++)
{
// ip_Worker[0] is the special CPU worker (if we need one)
if (ii == 0)
continue;
ip_Workers[ii]->LockStats();
workerLargestPrimeTested = ip_Workers[ii]->GetLargestPrimeTested();
// Ignore worker if it hasn't done any work.
if (workerLargestPrimeTested > 0)
{
// If this worker is waiting for work, then aasume that at least one worker
// will be working on the next chunk, so use its stats instead.
if (!ip_Workers[ii]->IsWaitingForWork(false))
{
// If there are multiple workers, this will be the largest prime tested
// where we know that all primes less than this prime have been tested.
if (workerLargestPrimeTested < largestPrimeTestedNoGaps)
largestPrimeTestedNoGaps = workerLargestPrimeTested;
}
if (workerLargestPrimeTested > largestPrimeTested)
largestPrimeTested = workerLargestPrimeTested;
}
primesTested += ip_Workers[ii]->GetPrimesTested();
workerCpuUS += ip_Workers[ii]->GetWorkerCpuUS();
ip_Workers[ii]->ReleaseStats();
}
if (ip_Workers[0] != NULL)
{
ip_Workers[0]->LockStats();
if (largestPrimeTested == 0)
{
largestPrimeTestedNoGaps = ip_Workers[0]->GetLargestPrimeTested();
largestPrimeTested = ip_Workers[0]->GetLargestPrimeTested();
}
primesTested += ip_Workers[0]->GetPrimesTested();
workerCpuUS += ip_Workers[0]->GetWorkerCpuUS();
ip_Workers[0]->ReleaseStats();
}
if (largestPrimeTestedNoGaps == PMAX_MAX_62BIT)
largestPrimeTestedNoGaps = largestPrimeTested;
}
uint64_t App::GetLargestPrimeTested(bool finishedNormally)
{
uint64_t largestPrimeTested = (finishedNormally ? 0 : il_AppMaxPrime);
uint64_t workerLargestPrimeTested;
if (!ib_HaveCreatedWorkers)
return il_MinPrime;
for (uint32_t ii=0; ii<=ii_TotalWorkerCount; ii++)
{
// ip_Worker[0] is the special CPU worker (if we need one)
if (ii == 0)
continue;
ip_Workers[ii]->LockStats();
workerLargestPrimeTested = ip_Workers[ii]->GetLargestPrimeTested();
// Ignore worker if it didn't do any work.
if (workerLargestPrimeTested > 0)
{
// If the program finished normally, then the largest prime tested across all
// workers tells us that all primes below that value have been tested. If not,
// then there might be gaps, so get the smallest prime from the workers that
// has been tested.
if (finishedNormally)
{
if (workerLargestPrimeTested > largestPrimeTested)
largestPrimeTested = workerLargestPrimeTested;
}
else
{
if (workerLargestPrimeTested < largestPrimeTested)
largestPrimeTested = workerLargestPrimeTested;
}
}
ip_Workers[ii]->ReleaseStats();
}
// If only the special worker has done work, then we will get the larger prime from it.
if (largestPrimeTested == 0 && ip_Workers[0] != NULL)
{
ip_Workers[0]->LockStats();
largestPrimeTested = ip_Workers[0]->GetLargestPrimeTested();
ip_Workers[0]->ReleaseStats();
}
return largestPrimeTested;
}

Get latest updates about Open Source Projects, Conferences and News.

Sign Up No, Thank you