我有一个项目,我试图运行,它浪费了超过30%的CPU。为什么呢?
代码用于快捷程序和一些提醒。
我正在使用visual studio 2017 c ++ windows 10 Core Intel / i7
命令行:
/ Yu“stdafx.h”/ GS / analyze- / W3 / Zc:wchar_t / ZI / Gm / Od / sdl /Fd"Debug\vc141.pdb“/ Zc:inline / fp:precise / D”WIN32 “/ D”_DEBUG“/ D”_CONSOLE“/ D”_UNICODE“/ D”UNICODE“/ errorReport:prompt / WX- / Zc:forScope / RTC1 / Gd / Oy- / MDd / Fa”Debug \“/ EHsc / nologo / Fo“Debug \”/Fp"Debug\Clear.pch“/ diagnostics:classic
代码:
#include "stdafx.h"
#include <Windows.h>
#include <shellapi.h>
bool pressed(int key) { return GetAsyncKeyState(key); }
namespace Main {
///to hide the console
void Main()
{
SetWindowPos(GetConsoleWindow(), nullptr, 0, 0, 0, 0, SWP_HIDEWINDOW);
}
///the shortcuts
void Main1() {
while (true) {
///Win-C = chrome
if (pressed(VK_LWIN)&&pressed('C')) system("chrome http://www.google.com");
///Menu = battery message
if (pressed(VK_APPS)) {
SYSTEM_POWER_STATUS a;
GetSystemPowerStatus(&a);
char title[15]; sprintf(title, "%d%% battery%s", a.BatteryLifePercent, a.BatteryFlag & 8 ? ", charging" : "");
char disp[100]; sprintf(disp, "You have %d hours and %d minutes left...", a.BatteryLifeTime / 3600 % 60, a.BatteryLifeTime / 60 % 60);
MessageBoxA(nullptr, disp, title, 0);
}
if (pressed(VK_LWIN) && pressed(VK_DELETE)) SHEmptyRecycleBinA(nullptr, "", 0);
if (pressed(VK_LWIN) && pressed('V')) system("C:\\Users\\steven\\source\\repos\\Clear\\Clear.sln");
if (pressed(VK_LWIN) && pressed('Z')) system("start cmd");
Sleep(GetDoubleClickTime());
}
}
///time
void Main2() {
while (true) {
SYSTEMTIME t;
GetSystemTime(&t);
if (t.wDayOfWeek != 4 && t.wDayOfWeek != 5 && t.wHour == 0 && t.wMinute == 0 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Its 00:00", "Sleep", 0);
if (t.wDayOfWeek == 0 && t.wHour == 15 && t.wMinute == 10 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the Technion", "תירגול", 0);
if ((t.wDayOfWeek == 1 || t.wDayOfWeek == 2) && t.wHour == 12 && t.wMinute == 25 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the lab", "Math is over", 0);
if (t.wDayOfWeek == 3 && t.wHour == 9 && t.wMinute == 35 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the class", "Math is over", 0);
if (t.wDayOfWeek == 4 && t.wHour == 10 && t.wMinute == 50 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the class", "Math is over", 0);
}
}
///the exit shortcut
void Main0() {
while (true) {
if (pressed(VK_LMENU) && pressed(VK_RMENU)) if (MessageBoxA(nullptr, "Do you want to exit?", "ShortCut", MB_YESNO|MB_ICONINFORMATION) == IDYES) exit(0);
Sleep(GetDoubleClickTime());
}
}
}
#include <thread>
using namespace std;
int main(){
using namespace Main;
thread a[4]={thread(Main), thread(Main0), thread(Main1), thread(Main2)};
for(thread& b:a) b.join();
return 0;}
答案 0 :(得分:1)
找出答案的正确方法是使用profiller;视觉工作室有一个内置,你应该做一些练习;因为它不仅会突出你的高CPU;还有哪个线程。
在此示例中,知道哪个线程足以回答您的问题。如果您打算编写线程代码,您应该掌握VS中的更多工具,因为线程变得非常复杂,非常快。